httpuploadtask.java
来自「MyUploader 是一款使用 http 协议(RFC 1867)用于上传文件」· Java 代码 · 共 656 行 · 第 1/2 页
JAVA
656 行
worker.interrupt();
} finally {
if (resizer != null) {
resizer.deleteTempDirectory();
}
if (out != null) {
try {
out.close();
} catch (IOException ioe) {
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException ioe) {
}
}
// if a zip has been created delete it
if (zipFile != null) {
zipFile.delete();
}
finished = true;
}
}
/**
* Writes the headers to the outputstream.
*
* @throws IOException If an IO error occurred.
*/
private void writeHeaders() throws IOException {
if (Parameters.getParameter(Parameters.COLDFUSION, false)) {
out.writeBytes("POST " + uploadURL.getFile() + " HTTP/1.0" + NEWLINE);
} else {
out.writeBytes("POST " + uploadURL.toString() + " HTTP/1.0" + NEWLINE);
}
out.writeBytes("Accept: */*" + NEWLINE);
out.writeBytes("User-Agent: MyUploader/1.8" + NEWLINE);
out.writeBytes("Content-type: " + "multipart/form-data; boundary=" + boundary + NEWLINE);
String cookie = Parameters.getParameter(Parameters.COOKIE, null);
if (cookie != null && !cookie.trim().equalsIgnoreCase("")) {
out.writeBytes("Cookie: " + cookie + NEWLINE);
}
if (proxyPasswordAuthentication != null) {
String loginData = new sun.misc.BASE64Encoder().encode ((proxyPasswordAuthentication.getUserName() + ":" + new String(proxyPasswordAuthentication.getPassword())).getBytes());
out.writeBytes("Proxy-Authorization: Basic " + loginData + NEWLINE);
}
out.writeBytes("Cache-Control: no-cache" + NEWLINE);
out.writeBytes("Pragma: no-cache" + NEWLINE);
out.writeBytes("Host: " + uploadURL.getHost() + NEWLINE);
out.writeBytes("Content-Length: " + new HTTPContentLengthCalculator().calculateContentLength(data, boundary.length() + 2) + NEWLINE + NEWLINE);
}
/**
* Writes an array of form input fields to the outputstream.
*
* @param formInputFields An array of FormInputField.
* @throws IOException If an error occurred.
*/
private void writeFormInputFields(FormInputField [] formInputFields) throws IOException {
for (int i = 0; i < formInputFields.length; i++) {
writeFormInputField(formInputFields[i]);
}
}
/**
* Writes a single form input field to the outputstream.
*
* @param formInputField The FormInputField.
* @throws IOException If an error occurred.
*/
private void writeFormInputField(FormInputField formInputField) throws IOException {
// write boundary
out.writeBytes(PREFIX);
out.writeBytes(boundary);
out.writeBytes(NEWLINE);
// write content header
out.writeBytes("Content-Disposition: form-data; name=\"" + formInputField.getName() + "\"" + NEWLINE);
out.writeBytes(NEWLINE);
out.writeBytes(formInputField.getValue());
out.writeBytes(NEWLINE);
}
/**
* Writes an array of form file fields to the outputstream.
*
* @param formFileFields An array of FormFileField.
* @throws IOException If an error occurred.
*/
private void writeFormFileFields(FormFileField [] formFileFields) throws IOException {
for (int i = 0; i < formFileFields.length; i++) {
filesProcessed++;
writeFormFile(formFileFields[i]);
}
}
/**
* Writes a FormFileField to the outputstream.
*
* @param formFile The FormFileField.
* @throws IOException If an IO error occurred.
*/
private void writeFormFile(FormFileField formFile) throws IOException {
File file = formFile.getFile();
// create inputstream
currentFileName = file.getName();
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
// write boundary
out.writeBytes(PREFIX);
out.writeBytes(boundary);
out.writeBytes(NEWLINE);
// write content header
out.writeBytes("Content-Disposition: form-data; name=\"" + formFile.getName() + "\"; filename=\"" + formFile.getURLEncodedUploadName() + "\"" + NEWLINE);
out.writeBytes("Content-Type: " + formFile.getContentType() + NEWLINE);
out.writeBytes(NEWLINE);
// write content
byte[] data = new byte[1024];
int len = 0;
while ((len = in.read(data, 0, data.length)) != -1) {
out.write(data, 0, len);
// update properties
bytesProcessed = bytesProcessed + len;
}
out.writeBytes(NEWLINE);
out.flush();
in.close();
}
/**
* Writes the last lines of the body to the outputstream.
*
* @throws IOException If an IO error occurred.
*/
public void writeFooters() throws IOException {
out.writeBytes(PREFIX);
out.writeBytes(boundary);
out.writeBytes(PREFIX);
out.writeBytes(NEWLINE);
out.flush();
}
/**
* Returns the return code (SUCCESS, CANCELLED, TECHNICAL_ERROR, CONNECTION_REFUSED).
*
* @return The return code.
*/
public int getReturnCode() {
return returnCode;
}
/**
* Returns the http status code from the server.
*
* @return The http status code from the server.
*/
public int getStatusCode() {
return statusCode;
}
/**
* Creates a zipfile and stores the zipfile in the temp directory
*
* @return True if zip file is created false is process is cancelled
* @throws IOException If an error occurred.
*/
private boolean createZipFile(String zipFileName) throws IOException {
processStatus = localeManager.getString("creatingZip") + "....";
FormFileField [] fileFields = data.getFormFileFields();
// sets the default values to 0
init();
// Create a buffer for reading the files
byte[] buf = new byte[1024];
try {
// Create the ZIP file
zipFile = new File(System.getProperty("java.io.tmpdir") + File.separator + zipFileName);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
// Compress the files
for (int i=0; i < fileFields.length & !abort; i++) {
FileInputStream in = new FileInputStream(fileFields[i].getFile());
filesProcessed++;
currentFileName = fileFields[i].getFile().getName();
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(fileFields[i].getUploadName()));
// Transfer bytes from the file to the ZIP file
int len = 0;
while ((len = in.read(buf)) > 0 && !abort) {
out.write(buf, 0, len);
bytesProcessed += len;
}
// Complete the entry
out.closeEntry();
in.close();
}
// Complete the ZIP file
out.close();
if (!abort) {
// create a new form field and put it in the formdata
FormFileField fff = new FormFileField("userfile[]", zipFile, "", ContentTypeMapper.getInstance().getContentType(zipFile));
data.removeAllFormFileFields();
data.addFormFileField(fff);
}
return !abort;
} catch (IOException e) {
Logger.log("HTTPUploadTask", "createZipFile()", e.toString());
throw e;
}
}
/**
* Checks if the files are currently uploaded.
*
* @return True if the files are being uploaded to the server.
*/
public synchronized boolean isUploading() {
return uploading;
}
/**
* Sets the default values to 0
*/
private void init() {
bytesProcessed = 0;
totalBytes = data.getTotalByteSizeOfFiles();
filesProcessed = 0;
}
/**
* Resizes images.
*
* @param size The new max length.
* @return True if the image is created, false with an abort
* @throws Exception If the image cannot be resized.
*/
private boolean resizeImages(int size) throws Exception {
processStatus = localeManager.getString("resize") + "....";
FormFileField [] fileFields = data.getFormFileFields();
int compressionQuality = Parameters.getParameter(Parameters.COMPRESSION_QUALITY, 75);
if (compressionQuality < 0 || compressionQuality > 100) {
compressionQuality = 75;
}
// sets the default values to 0
init();
// Compress the files
for (int i=0; i < fileFields.length & !abort; i++) {
filesProcessed++;
currentFileName = fileFields[i].getFile().getName();
if (fileFields[i].getFile().toString().toLowerCase().endsWith("jpg") || fileFields[i].getFile().toString().toLowerCase().endsWith("jpeg")) {
File f = resizer.getScaleImage(fileFields[i].getFile(), fileFields[i].getUploadDirectory(), size, ((float)compressionQuality/100));
fileFields[i].setFile(new File(f.getAbsolutePath()));
}
}
return !abort;
}
/**
* Add the bytes who are processed.
*
* @param bytes The bytes processed.
*/
public void addBytesProcessed (int bytes) {
bytesProcessed += bytes;
}
/**
* Returns the custom error message.
*
* @return the custom error message.
*/
public String getErrorMessage() {
return errorMessage;
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?