/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package upload;
import java.io.File;
import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.MultipartPostMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
public class HttpClientUtile {
public String uploadFiles(String strUrl, String[] strFiles)
{
String strResponse = null;
HttpClient httpClient = new HttpClient();
MultipartPostMethod multipartPostMethod = new MultipartPostMethod(strUrl);
try {
for (int i = 0; i < strFiles.length; i++) {
multipartPostMethod.addPart(new FilePart("file"+i,new File(strFiles[i])));
}
int statusCode = httpClient.executeMethod(multipartPostMethod);
if (statusCode == 200) {
strResponse = multipartPostMethod.getResponseBodyAsString();
}
} catch (Exception e){
e.printStackTrace();
}
finally
{
multipartPostMethod.releaseConnection();
}
return strResponse;
}
public String uploadFiles(String strUrl,String strFrom, String strFiles)
{
String strResponse = null;
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(strUrl);
try {
FilePart filePart = new FilePart("file","aa.txt",new File(strFiles));
MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(new Part[]{new StringPart("HIDDEN","from",strFrom),filePart},postMethod.getParams());
postMethod.addParameter(new NameValuePair("from",strFrom));
postMethod.setRequestEntity(multipartRequestEntity);
httpClient.getParams().setContentCharset("UTF-8");
int statusCode = httpClient.executeMethod(postMethod);
if (statusCode == 200) {
strResponse = postMethod.getResponseBodyAsString();
}
} catch (Exception e){
e.printStackTrace();
}
finally
{
postMethod.releaseConnection();
}
return strResponse;
}
/**
* @category 上传附件
* @param strUrl
* @param strFiles
* @return 返回状态码 200 正常
* @throws Exception
*/
public String uploadFiles(String strUrl,String attachments) throws Exception
{
String strResponse = null;
HttpClient httpClient = new HttpClient();
MultipartPostMethod postMethod = new MultipartPostMethod(strUrl.trim());
try {
if (null != attachments && attachments.trim().length()>0) {
String [] strArr = attachments.trim().split("\\|");
for (int i = 0; i < strArr.length; i++) {
if (null!= strArr[i] && strArr[i].trim().length()>0) {
String fileName = strArr[i].trim();
fileName = fileName.replaceAll("\\\\", "/").replaceAll("//","/");
fileName = fileName.replaceAll("\\\\", "/").replaceAll("//","/");
String[] strTmpNameArr = fileName.split("/");
if (strTmpNameArr.length>0) {
fileName = strTmpNameArr[strTmpNameArr.length-1];
postMethod.addPart(new FilePart(fileName,new File(strArr[i].trim())));
}
}
}
}
else {
return "File can not be null";
}
httpClient.getParams().setContentCharset("UTF-8");
int statusCode = httpClient.executeMethod(postMethod);
if (statusCode == 200) {
strResponse = postMethod.getResponseBodyAsString();
}
return strResponse;
} catch (Exception e){
throw e;
}
finally
{
postMethod.releaseConnection();
}
}
public static void main(String[] args) {
HttpClientUtile testSendData = new HttpClientUtile();
try {
String strUploadFile = testSendData.uploadFiles("http://172.16.22.61:8068/isite/uploadLog", "d://project.txt");
System.out.println("strUploadFile:"+strUploadFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
用到的Jar包:commons-httpclient-3.0.1.jar、commons-logging-1.1.1.jar、commons-beanutils-1.8.0-BETA.jar和commons-codec.jar;这个网上很多,很容易就可以找到;
服务端接收的代码:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.ithings.irtu.sync.controller;
import com.ithings.irtu.utils.SystemConstants;
import com.ithings.util.CommUtils;
import java.io.File;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
/**
*
*/
public class UploadLogServlet extends HttpServlet{
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
doPost(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
PrintWriter out = null;
String flag = "0";
File saveFile = null;
try {
out = resp.getWriter();
String fileName = req.getParameter("name");
if(CommUtils.isNull(fileName)){
fileName = "upgrade" + CommUtils.convertDateToString(new Date(), "yyyy-MM-dd-HH-mm-ss") + ".txt";
}
String filePath = SystemConstants.UPGRADE_LOG_FILE_PATH + fileName;
File dir = new File(SystemConstants.UPGRADE_LOG_FILE_PATH);
if(!dir.exists()){
dir.mkdirs();
}
DiskFileUpload diskFileUpload = new DiskFileUpload();
///设置可上传文件的最大尺寸
diskFileUpload.setSizeMax(20*1024*1024);
//设置缓冲区大小,这里是2kb
diskFileUpload.setSizeThreshold(2048);
//设置临时目录
diskFileUpload.setRepositoryPath(SystemConstants.UPGRADE_LOG_FILE_PATH);
//获取所有文件
List listFiles = diskFileUpload.parseRequest(req);
if (null != listFiles && listFiles.size() > 0) {
for (int i = 0; i < listFiles.size(); i++) {
FileItem fileItem = (FileItem)listFiles.get(i);
if (null != fileItem.getName()) {
saveFile = new File(SystemConstants.UPGRADE_LOG_FILE_PATH,fileItem.getName());
fileItem.write(saveFile);
}else{
saveFile = new File(filePath);
fileItem.write(saveFile);
}
}
}
if(saveFile != null && saveFile.length() == 0){
flag = "1";
saveFile.delete();
}
} catch (Exception e) {
Logger.getLogger(UploadLogServlet.class.getName()).log(Level.SEVERE, null, e);
flag = "1";
}finally{
if(out != null){
out.write(flag);
out.flush();
out.close();
}
}
}
}
其中SystemConstants.UPGRADE_LOG_FILE_PATH表示文件存放目录,你们可以定义自己的位置;