(原)仿HttpClient實現HTTP上傳

話不多說了,大家看代碼吧

模擬上傳提交,發送端
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
* HTTP上傳文件實現類
*/
public class HttpUpload {

/** 緩衝大小 */
private static final int BYTE_BUFFER_SIZE = 1024;

/** 分隔符 */
private static final String BOUNDARY = "---------------------------7d4a6d158c9";

/** Form名 */
private String formName;

/**
* @return the formName
*/
public String getFormName() {
return formName;
}

/**
* @param formName
* the formName to set
*/
public void setFormName(String formName) {
this.formName = formName;
}

/**
* 得到上傳的HTTP頭
*
* @param fileName 文件名
*/
private byte[] getHttpUploadHeader(String fileName) {

if (formName == null || formName.length() == 0) {
formName = "fileDefaultForm";
}

StringBuilder builder = new StringBuilder();
builder.append("--").append(BOUNDARY).append("\r\n").append(
"Content-Disposition: form-data; name=\"").append(formName)
.append("\"; filename=\"").append(fileName).append("\"\r\n")
.append("Content-Type: application/octet-stream\r\n\r\n");
return builder.toString().getBytes();
}

/**
* 上傳主調方法
*/
public void upload(String urlPath, String filePath) throws IOException {

URL url = null;
File file = null;
FileInputStream inputStream = null;

HttpURLConnection connection = null;

try {
url = new URL(urlPath);
file = new File(filePath);
inputStream = new FileInputStream(file);

connection = (HttpURLConnection) url.openConnection();

connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");

int total = inputStream.available();

byte[] dataStart = getHttpUploadHeader(file.getName());
byte[] dataEnd = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();

// 設置表單類型和分隔符
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

// 設置內容長度
connection.setRequestProperty("Content-Length", String.valueOf(dataStart.length + total + dataEnd.length));

OutputStream postStream = connection.getOutputStream();

postStream.write(dataStart);

int current = 0;
while (current < total) {

byte[] b = new byte[BYTE_BUFFER_SIZE];

if (total < BYTE_BUFFER_SIZE + current) {
inputStream.read(b, 0, total - current - 1);
} else {
inputStream.read(b, 0, BYTE_BUFFER_SIZE);
}

postStream.write(b);

current += BYTE_BUFFER_SIZE;
}

postStream.write(dataEnd);

postStream.flush();
postStream.close();

// Send Stream
InputStream is = connection.getInputStream();
is.close();

} catch (MalformedURLException e) {
e.printStackTrace();
throw e;
} catch (FileNotFoundException e) {
e.printStackTrace();
throw e;
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (connection != null) {
connection.disconnect();
}

}
}

public static void main(String args[]) throws Exception {
new HttpUpload().upload(
"http://localhost:8085/FileUploadAdvance/BigFileUploadServlet",
"D:\\face.jpg");
}
}


測試的時候用apache common中的fileupload組件接收
package org.test;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
* Servlet implementation class BigFileUploadServlet
*/
public class BigFileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

private static final String WORK_DIR_PATH = "workDir";

private File workDir = null;

private static final String DESTINATION_DIR_PATH = "destDirPath";

private File destDir = null;

private String destDirPath = null;

/**
* @see HttpServlet#HttpServlet()
*/
public BigFileUploadServlet() {
super();
}

public void init(ServletConfig config) throws ServletException {

String workDirPath = config.getInitParameter(WORK_DIR_PATH);

destDirPath = config.getInitParameter(DESTINATION_DIR_PATH);

if (workDirPath != null && workDirPath.length() > 0) {
workDir = new File(workDirPath);
if (!workDir.exists()) {
workDir.mkdirs();
}
}

if (destDirPath != null && destDirPath.length() > 0) {
destDir = new File(destDirPath);
if (!destDir.exists()) {
destDir.mkdirs();
}
}
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
process(request, response);
} catch(Exception e) {
System.out.println(e);
}
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
try {
process(request, response);
} catch(Exception e) {
System.out.println(e);
}
}

private void process(HttpServletRequest request, HttpServletResponse response) throws Exception {

DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(500);
factory.setRepository(workDir);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);

//ActionContext.initCurrentContext(request, response);

//upload.setProgressListener(new ProgressAdapter(ActionContext.getActionContext()));
//upload.setSizeMax(200);

// Parse the request
List<FileItem> items = upload.parseRequest(request);

for (FileItem item : items){

if (!item.isFormField()) {
String fieldName = item.getFieldName();
String fileName = getFileName(item.getName(), "\\");
fileName = getFileName(fileName, "/");

String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
item.write(new File(destDirPath + fileName));
}
}
}

private String getFileName(String originName, String searchChar) {

int pathIndex = originName.lastIndexOf(searchChar);

if (pathIndex != -1) {
return originName.substring(pathIndex + searchChar.length());
}
return originName;
}

}


web.xml中配置如下
<servlet>
<description></description>
<display-name>BigFileUploadServlet</display-name>
<servlet-name>BigFileUploadServlet</servlet-name>
<servlet-class>org.test.BigFileUploadServlet</servlet-class>
<init-param>
<param-name>workDir</param-name>
<param-value>E:/temp/</param-value>
</init-param>
<init-param>
<param-name>destDirPath</param-name>
<param-value>E:/fileTemp/</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>BigFileUploadServlet</servlet-name>
<url-pattern>/BigFileUploadServlet</url-pattern>
</servlet-mapping>
發佈了12 篇原創文章 · 獲贊 1 · 訪問量 2536
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章