SpringBoot + AjaxFileUpload.js 实现文件上传
AjaxFileUpload.js并不是一个很出名的插件,原理是创建隐藏的表单和iframe然后用JS去提交,获得返回值。
ajaxFileUpload是一个异步上传文件的jQuery插件
使用步骤:
前端代码:
一、先引入jQuery与ajaxFileUpload插件。注意先后顺序(自己到网上去下载ajaxFileUpload.js文件)
<script type="text/javascript" src="/res/js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="/res/js/ajaxfileupload.js?v=1"></script>
二、HTML代码
<input type="file" name="fileExcel" id="fileExcel" onchange="submitFile()"/>
三、js代码
function submitFile() {
$.ajaxFileUpload({
url: "/index/excel_import", //上传处理程序地址
secureuri: false, // 是否启用安全提交,默认为false。
fileElementId: "fileExcel", // 需要上传的文件域的ID,input的id,我这里为file
dataType: 'json', // 服务器返回的数据类型。可以为xml,script,json,html。如果不填写,jQuery会自动判断。
type: 'post', // 请求类型
success: function (response, status) {
$("#file").val("");
alert("上传成功!");
},
error: function (response, status, e) {
$("#file").val("");
alert("服务器出现异常:" + e);
}
});
}
接下来后端代码
Spring Boot 默认装配的了 MultipartAutoConfiguration,所以我们不用配置
四、上传接口,将图片文件保存到指定地址
@RequestMapping(value = "/excel_import",method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> excelImport(@RequestParam MultipartFile fileExcel) {
Map<String, Object> map = new HashMap<>();
InputStream is = null;
try {
is = fileExcel.getInputStream();
// 文件全称
String fileName = fileExcel.getOriginalFilename();
int index;
byte[] bytes = new byte[1024];
// 保存到本地地址,需要拼接上fileName,不然会报错
String destination = "D:\\uploadImage\\tengJun\\"+fileName;
FileOutputStream downloadFile = new FileOutputStream(destination);
while ((index = is.read(bytes)) != -1) {
downloadFile.write(bytes, 0, index);
downloadFile.flush();
}
downloadFile.close();
is.close();
} catch (IOException e1) {
e1.printStackTrace();
map.put("result",false);
map.put("errorMsg","文件格式有误!");
return map;
} catch (Exception e) {
e.printStackTrace();
map.put("result",false);
map.put("errorMsg","导入失败!");
return map;
}
map.put("result",true);
map.put("errorMsg","参数错误!");
return map;
}
就这样,完美的实现了文件上传!!!
容易出错的地方总结:
- js引用顺序问题,应该先引入jquery,再引入ajaxfileupload。
- input的name="fileExcel" 应该跟后台接收参数对应