使用servlet文件上传
String serverPath = this.getServletContext().getRealPath("/");
JSONObject jsonObject = new JSONObject();
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
if (!ServletFileUpload.isMultipartContent(req)) {
return;
}
List<FileItem> list = upload.parseRequest(req);
for (FileItem file : list) {
if (!file.isFormField() && "file".equals(file.getFieldName())) {
String fileName = file.getName();
fileName = fileName
.substring(fileName.lastIndexOf("\\") + 1);
String extName = fileName.substring(fileName
.lastIndexOf("."));
String uuid = UUIDGenerator.generate();
String newName = uuid + extName;
FileUtils.copyInputStreamToFile(file.getInputStream(),
new File(serverPath + "/" + newName));
LOG.info(serverPath + "/" + newName);
jsonObject.put("result", "OK");
break;
}
}
} catch (FileUploadException e) {
LOG.info(OfflineCode.UPLOAD_FILE_ABNORMAL.toString());
LOG.info(e.getMessage(), e);
jsonObject.put("result", "ERROR");
} finally {
out.println(jsonObject.toString());
out.close();
}