前言
javaEE开发中比较常用的form表单提交,因为表单提交的方式基本是json,这样在后台直接可以通过request.Pramater()获取,但是如果涉及到文件提交呢?一种常用的方式就是以流的方式提交,这样一来,后台是无法直接获取的,具体步骤如下。
前端
function submit(){
var formData =
new FormData();
formData.append(
'file', $(
'#file')[
0].files[
0]);
formData.append(
'description',$(
"#description").val());
$.ajax({
type:
"POST",
url:
"file/upload",
data:formData,
contentType:
false,
processData:
false,
success:
function(data) {
data =
JSON.parse(data);
if(data.success){
alert(
"上传成功");
}
else{
alert(data.codes);
}
}
});
}
后端
private static final int MEMORY_THRESHOLD =
1024 *
1024 *
3;
private static final int MAX_FILE_SIZE =
1024 *
1024 *
50;
private static final int MAX_REQUEST_SIZE =
1024 *
1024 *
100;
private static final String UPLOAD_DIRECTORY =
"fileDir";
DiskFileItemFactory factory =
new DiskFileItemFactory();
factory.setSizeThreshold(MEMORY_THRESHOLD);
factory.setRepository(
new File(System.getProperty(
"java.io.tmpdir")));
ServletFileUpload upload =
new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(MAX_REQUEST_SIZE);
String uploadPath = request.getServletContext().getRealPath(
"./") + UPLOAD_DIRECTORY;
File uploadDir =
new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try {
List<FileItem> formItems = upload.parseRequest(request);
Map<String, Object> params =
new HashMap<String, Object>();
if (formItems !=
null && formItems.size() >
0) {
for (FileItem item : formItems) {
if (item.isFormField()) {
params.put(item.getFieldName(),item.getString());
}
else {
String fileName =
new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
String fileSize = String.valueOf(item.getSize());
File storeFile =
new File(filePath);
item.write(storeFile);
}
}
setParams(params);
}
}
catch (FileUploadException e) {
e.printStackTrace();
return null;
}
后记
今天不想说什么了,有点累。
参考文章
http://blog.csdn.net/clementad/article/details/49717397 https://www.leiphone.com/news/201705/HeBxL297H3VU1nf2.html http://www.ruanyifeng.com/blog/2012/08/file_upload.html