public class UploadClient {
public static void main(String[] args) throws ClientProtocolException,
IOException {
args = new String[] { "D:\\test.exe" };
if (args.length != 1) {
System.out.println("File path not given");
System.exit(1);
}
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost(
"http://localhost:8080/test_web/upload");
FileBody bin = new FileBody(new File(args[0]));
StringBody comment = new StringBody("A binary file of some kind",
ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("bin", bin).addPart("comment", comment).build();
httppost.setEntity(reqEntity);
System.out
.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: "
+ resEntity.getContentLength());
System.out.println(EntityUtils.toString(resEntity));
}
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}
public class UploadServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final long FILE_MAX_SIZE = 1024 * 1024 * 200;
private static final String FILE_SAVE_PATH = "D:\\test\\";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("do get");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse resp)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
RequestContext req = new ServletRequestContext(request);
if (FileUpload.isMultipartContent(req)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);
fileUpload.setHeaderEncoding("UTF-8");
fileUpload.setFileSizeMax(FILE_MAX_SIZE);
List<FileItem> items = new ArrayList<FileItem>();
try {
items = fileUpload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
Iterator<FileItem> it = items.iterator();
while (it.hasNext()) {
FileItem fileItem = (FileItem) it.next();
if (fileItem.isFormField()) {
System.out.println(fileItem.getFieldName()
+ " "
+ fileItem.getName()
+ " "
+ new String(fileItem.getString().getBytes(
"ISO-8859-1"), "GBK"));
} else {
System.out.println(fileItem.getFieldName() + " "
+ fileItem.getName() + " " + fileItem.isInMemory()
+ " " + fileItem.getContentType() + " "
+ fileItem.getSize());
if (fileItem.getName() != null && fileItem.getSize() != 0) {
File fullFile = new File(fileItem.getName());
File newFile = new File(FILE_SAVE_PATH
+ fullFile.getName());
try {
fileItem.write(newFile);
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("no file choosen or empty file");
}
}
}
}
}
}