1.ajax实现文件上传
前端
<div>
<form id='upload-form' onsubmit='return false' class='m-2'>
<div class='row mb-2'>
<div class='col-sm-12'><input id='files' type='file' name='file' class='col-sm-10 form-control mb-2'></div>
</div>
<div class='row mb-2'>
<div class='col-sm-12' id='show-box'>
</div>
</div>
</form>
</div>
//使用的是jQuery
var fileData = new FormData();
fileData.append("file",imgFile[0]);
fileData.append("url",encodeURI(nowPathsLast));
$.ajax({url:"/file/uploadPath.do", method:"post",
data:fileData, contentType:false, processData:false, cache:false,
dataType:"json",
success(res){
console.log("响应数据",res)
if (res.code === 200) {
//上传成功 真实请求路径
/*var realUrl = res.data.url;
//发送请求更新资源表
console.log(realUrl)*/
parent.modelHide();
refreshTable();
} else {
alert(res.msg)
}
},
xhr:function () {
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress",function (ev) {
//loaded已上传大小
//ev.total总大小
console.log(Math.round(ev.loaded/ev.total*100)+"%",ev.lengthComputable)
},false)
return xhr;
}
})
后台
private final ResourceService resourceService = new ResourceServiceImpl();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url = request.getParameter("url");
//前端用encodeURI()编码,后端用URLDecoder.decode解码
if (url == null){
HttpUtil.responseJson(response,-1,"参数缺失",null);
return;
}
String decode = URLDecoder.decode(url, "UTF-8");
System.out.println("转码后的"+decode);
String rootDir = url + "/";
System.out.println(rootDir);
//获取所有上传文件
Part part = request.getPart("file");
if (part == null){
HttpUtil.responseJson(response,0,"上传错误!请检查。",null);
return;
}
int PathDirId = 0;
try {
PathDirId = resourceService.findIdByPath(url);
} catch (Exception e) {
e.printStackTrace();
HttpUtil.responseJson(response,-1,"error",null);
return;
}
int endIndex = part.getSubmittedFileName().lastIndexOf(".");
String suffix = part.getSubmittedFileName().substring(endIndex + 1);
String fileName = UUID.randomUUID().toString().replace("-","").concat(".").concat(suffix);
//文件真实保存路径
String FileRealPath = this.getServletContext().getRealPath(rootDir + fileName);
//文件请求路径
String requestPath = rootDir + fileName;
//保存文件
try {
part.write(FileRealPath);
// 同步资源表
Integer isAdd = resourceService.addResource(requestPath,part.getSubmittedFileName(),1,PathDirId,"图片");
if (isAdd <= 0){
HttpUtil.responseJson(response,1,"同步资源表失败",null);
return;
}
} catch (Exception e){
HttpUtil.responseJson(response,0,"上传错误!请检查。",null);
return;
}
Map<String,Object> map = new HashMap<>();
map.put("url",requestPath);
map.put("alt",part.getSubmittedFileName());
//回写保存路径
HttpUtil.responseJson(response,200,"保存成功",map);
}
值得注意的是当我们表单中除了文件之外的数据如果包含有中文的话则会出现乱码
解决方法:
- 前端使用
encodeURI(str)
对字符串进行编码 - 后台使用
URLDecoder.decode(str, "UTF-8");
进行解码