要使用httpclient必须引入commons-codec.jar,commons-io.jar,comons-httpclent.jar。
客户端上传代码:
try {
File sendFile = new File(filePath);
PostMethod postMethod = new PostMethod(sendURL.toString());
Part[] parts = { new FilePart(sendFile.getName(), sendFile) };// 构建发送的文件对象
MultipartRequestEntity reqEntity = new MultipartRequestEntity(
parts, postMethod.getParams());
postMethod.setRequestEntity(reqEntity);
HttpClient httpClient = new HttpClient();
int statusCode = httpClient.executeMethod(postMethod);
if (statusCode == HttpStatus.SC_OK) {
System.out.println("文件发送成功!");
} else {
System.out.println("文件发送失败");
}
}
服务端接收上传文件,使用commons-fileupload组件,用servlet来处理
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class ImageScanUploadServlet implements Servlet {
private String uploadPath = "D:\\temp"; // 上传文件的目录
private String tempPath = "D:\\temp\\buffer\\"; // 临时文件目录
private File tempPathFile;
@Override
public void destroy() {
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void init(ServletConfig arg0) throws ServletException {
File uploadFile = new File(uploadPath);
if (!uploadFile.exists()) {
uploadFile.mkdirs();
}
File tempPathFile = new File(tempPath);
if (!tempPathFile.exists()) {
tempPathFile.mkdirs();
}
}
@Override
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
try {
HttpServletRequest request = (HttpServletRequest) arg0;
HttpServletResponse response = (HttpServletResponse) arg1;
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(4096);// 设置缓冲区大小,这里是4kb
factory.setRepository(tempPathFile);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB
List<FileItem> items = upload.parseRequest(request);
for (FileItem fi : items) {
String fileName = fi.getName();
if (fileName != null) {
File fullFile = new File(fi.getName());
File savedFile = new File(uploadPath, fullFile.getName());
fi.write(savedFile);
}
System.out.println("upload succeed");
}
response.getWriter().write("upload succeed");
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}