httpuploadtask.java
来自「MyUploader 是一款使用 http 协议(RFC 1867)用于上传文件」· Java 代码 · 共 656 行 · 第 1/2 页
JAVA
656 行
/*
* Copyright 2005-2007 JavaAtWork All rights reserved.
* Use is subject to license terms.
*/
package javaatwork.myuploader.net;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ConnectException;
import java.net.PasswordAuthentication;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javaatwork.myuploader.domain.FormData;
import javaatwork.myuploader.domain.FormFileField;
import javaatwork.myuploader.domain.FormInputField;
import javaatwork.myuploader.utils.LocaleManager;
import javaatwork.myuploader.utils.Logger;
import javaatwork.myuploader.utils.Parameters;
import javaatwork.myuploader.utils.ResizeManager;
import javaatwork.myuploader.utils.SwingWorker;
/**
* Task for sending files to a Web Server. The protocol used is http/https.
*
* @author Johannes Postma
*/
public class HTTPUploadTask {
private DataOutputStream out = null;
private Socket socket = null;
private int filesProcessed = 0;
private long totalBytes = 0L;
private long bytesProcessed = 0L;
private String currentFileName = "";
private long begin = 0L;
private SwingWorker worker = null;
private boolean finished = false;
private String boundary = null;
private URL uploadURL = null;
private final static String NEWLINE = "\r\n";
private LocaleManager localeManager = null;
private String processStatus = "";
private PasswordAuthentication proxyPasswordAuthentication = null;
private NetUtils netUtils = null;
private FormData data = null;
private boolean abort = false;
private boolean uploading = false;
private File zipFile = null;
private ResizeManager resizer = null;
private String errorMessage = null;
private int returnCode = 0;
private int statusCode = 0;
public static final int SUCCESS = 0;
public static final int CANCELLED = 1;
public static final int CONNECTION_REFUSED = 2;
public static final int CUSTOM_ERROR = 3;
public static final int TECHNICAL_ERROR = 9;
/**
* The boundary prefix.
*/
private final String PREFIX = "--";
/**
* Creates a new HTTPUploadTask with a AppletContext.
*
* @param uploadURL The upload url of the server.
* @param formData The FormData, the data to be uploaded.
* @param proxyPasswordAuthentication PasswordAuthentication.
*/
public HTTPUploadTask(URL uploadURL, FormData formData, PasswordAuthentication proxyPasswordAuthentication) {
super();
localeManager = LocaleManager.getInstance();
this.netUtils = new NetUtils();
this.proxyPasswordAuthentication = proxyPasswordAuthentication;
this.uploadURL = uploadURL;
this.data = formData;
boundary = "--------------------" + Long.toString(System.currentTimeMillis(), 16);
}
/**
* Returns the number of processed bytes.
*
* @return The number of processed bytes.
*/
public synchronized long getBytesProcessed() {
return bytesProcessed;
}
/**
* Returns the number of bytes of the files to be sent.
*
* @return The number of bytes of the files to be sent.
*/
public synchronized long getTotalBytes() {
return totalBytes;
}
/**
* Return the number of files to be sent.
*
* @return The number of files to be sent.
*/
public synchronized int getFiles() {
return data.getNumberOfFormFileFields();
}
/**
* Returns the number of processed files.
*
* @return The number of processed files.
*/
public synchronized int getFilesProcessed() {
return filesProcessed;
}
/**
* Returns the elapsed time in ms.
*
* @return The elapsed time ms.
*/
public synchronized int getElapsedTime() {
return (int) (System.currentTimeMillis() - begin);
}
/**
* Returns the rest time in ms.
*
* @return The elapsed time in ms.
*/
public synchronized int getTimeLeft() {
return (int) ((totalBytes - getBytesProcessed()) / (double) getBytesProcessed() * getElapsedTime());
}
/**
* Returns the percentcompleted of the task.
*
* @return The percentcompleted.
*/
public synchronized int getPercentCompleted() {
return (int) (getBytesProcessed() / (double) totalBytes * 100);
}
/**
* Returns the filename of the file that is currently be uploaded.
*
* @return The name of the currently uploaded file.
*/
public synchronized String getCurrentFileName() {
return currentFileName;
}
/**
* Returns the status of the upload process.
*
* @return The status.
*/
public synchronized String getProcessStatus() {
return processStatus;
}
/**
* Starts the task (upload).
*/
public void start() {
worker = new SwingWorker() {
public Object construct() {
upload();
return null;
}
};
worker.start();
}
/**
* Interrupts the task.
*/
public void stop() {
// if no connection is available (e.g. the client is connecting)
// pressing
// the cancel button generates otherwise a NullPointerException
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
}
}
abort = true;
returnCode = CANCELLED;
}
/**
* Returns true if the task is finished.
*
* @return True if the task is finished.
*/
public boolean finished() {
return finished;
}
/**
* Does the real upload.
*/
public void upload() {
begin = System.currentTimeMillis();
try {
int maxImageSize = Parameters.getParameter(Parameters.MAX_IMAGE_SIZE, -1);
if (maxImageSize != -1) {
resizer = new ResizeManager(this);
if (!resizeImages(maxImageSize)) {
return;
}
}
String zipFileName = Parameters.getParameter(Parameters.ZIP_FILE, null);
if (zipFileName != null) {
if (!createZipFile(zipFileName)) {
return;
}
}
// sets the default values to 0
init();
// needed for the progress dialog
uploading = true;
processStatus = localeManager.getString("connecting") + "....";
socket = netUtils.createSocket(uploadURL, proxyPasswordAuthentication);
out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
// write the headers to the outputstream
writeHeaders();
writeFormInputFields(data.getFormInputFields());
processStatus = localeManager.getString("uploading") + "....";
writeFormFileFields(data.getFormFileFields());
writeFooters();
processStatus = localeManager.getString("waiting_for_response") + "....";
HTTPParser httpParser = new HTTPParser(socket.getInputStream(), "ISO-8859-1");
Logger.log("HTTPUploadTask", "upload()", httpParser.getStatusLine());
if (httpParser.getStatusCode() == 200) {
returnCode = SUCCESS;
statusCode = 200;
if (Parameters.getParameter(Parameters.SHOW_CUSTOM_ERROR_MESSAGES, false)) {
errorMessage = httpParser.getBody();
if (errorMessage != null && !errorMessage.trim().equals("")) {
returnCode = CUSTOM_ERROR;
}
}
} else {
returnCode = TECHNICAL_ERROR;
statusCode = httpParser.getStatusCode();
}
} catch (UnknownHostException uhe) {
Logger.log("HTTPUploadTask", "upload()", uhe.toString());
if (!abort) {
returnCode = TECHNICAL_ERROR;
}
finished = true;
worker.interrupt();
} catch (ConnectException ce) {
Logger.log("HTTPUploadTask", "upload()", ce.toString());
if (!abort) {
returnCode = CONNECTION_REFUSED;
}
finished = true;
worker.interrupt();
} catch (IOException ioe) {
Logger.log("HTTPUploadTask", "upload()", ioe.toString());
if (!abort) {
returnCode = TECHNICAL_ERROR;
}
finished = true;
worker.interrupt();
} catch (Throwable t) {
Logger.log("HTTPUploadTask", "upload()", t.toString());
returnCode = TECHNICAL_ERROR;
finished = true;
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?