1.问题
之前写过上传文件了,利用$.ajaxUpload()方法,但是发现在HAP框架下,根本不吃这一套,出现了一个框架内部错误,应该是权限或者某些字段没有被赋值报错,反正框架的缺点在这里我是深深的体会到了。
2.解决方法
前端js
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/exportFile1" id="uploads_file" method="post" enctype="multipart/form-data">
<input id="excelFile" type="file" name="excelFile"
style="border:none;padding-bottom:10px;">
</form>
<span id="fileName">请选择文件!</span>
<input type="submit" id="btn_export" value="上传">
<script>
$("#btn_export").click(function () {
var name = $("#excelFile").val();
var f = name.endsWith(".xlsx") || name.endsWith(".xls") || name.endsWith(".csv");
console.log(f);
if(!f){
alert('文件格式不正确,应该为Excel表格')
}else {
var formData = new FormData($("#uploads_file")[0]);
$.ajax({
url: "/exportFile1",
type: "POST",
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (result) {
console.log(result);
}
});
}
});
</script>
</body>
</html>
后台处理
@RequestMapping(value = "/exportFile1",method = RequestMethod.POST)
@ResponseBody
public String exportFile1(HttpServletRequest request, HttpServletResponse response
){
System.out.println("来啊1");
FileItemFactory fileItemFactory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fileItemFactory);
try {
List<?> items = upload.parseRequest(request);
Iterator iter = items.iterator();
while(iter.hasNext()){
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString();
} else {
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize(); System.out.println("ServletFileUpload 的文件:"+fileName);
try {
item.write(uploadedFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
return "scuess";
}