前言
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; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 50; // 50MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 100; // 100MB
// 上传文件存储目录
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) {
// TODO Auto-generated catch block
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