Ajax很好用,但是在上传文件这边却总是会出问题。例如,现在想上传一张图片,希望前台无刷新操作,使用Ajax上传,后台接收不到相应的类型,导致上传失败,但是如果使用input和submit组合又会出现页面刷新的情况,百般折磨后找到了一个新的工具:Simple-Ajax-Uploader.
简单示例
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button id="btnUpload">上传图片</button>
<script type="text/javascript" src="SimpleAjaxUploader.js"></script>
<script type="text/javascript">
var btnUpload = document.getElementById("btnUpload");
var uploader = new ss.SimpleUpload({
button: btnUpload,
url: "http://192.168.1.105:8080/api/file/upload/image",
name: "uploadImage",
multiple: true,
allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
responseType: 'json',
onSubmit: function () {
},
onComplete: function (filename, response) {
console.log(filename);
console.log(response);
},
onError: function (error) {
console.log(error);
}
});
</script>
</body>
</html>
后台代码
/**
* 单张图片上传接口
*
* @param request 请求
* @param uploadImage 要上传的图片
* @return 上传成功返回图片的URL;上传失败返回“上传失败”;
*/
@ApiOperation(value = "单张图片上传接口")
@RequestMapping(value = "/upload/image", method = RequestMethod.POST)
@ResponseBody
@Transactional
public HttpResponse<String> uploadImage(HttpServletRequest request, MultipartFile uploadImage) {
HttpResponse<String> httpResponse = new HttpResponse<>();
if (null != uploadImage) {
String uploadImagePath = request.getSession().getServletContext().getRealPath("/") + "/file/upload/image/";
File uploadImageDir = new File(uploadImagePath);
if (!uploadImageDir.exists()) {
boolean success = uploadImageDir.mkdir();
if (success) {
System.out.println("文件夹创建成功");
} else {
System.out.println("文件夹创建失败");
}
}
// 初始化图片信息
Image image = initImage(uploadImage);
// 要保存的图片
File saveToServerImage = new File(uploadImagePath + image.getName());
try {
// 将要上传的图片信息写入要保存的图片中
uploadImage.transferTo(saveToServerImage);
// 将图片信息存储到数据库
Image saveToDbImage = imageJPA.save(image);
if (null != saveToDbImage) {
httpResponse.setCode(1);
httpResponse.setData(saveToDbImage.getUrl());
httpResponse.setMsg("图片上传成功");
return httpResponse;
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
httpResponse.setCode(0);
httpResponse.setData("");
httpResponse.setMsg("图片上传失败");
return httpResponse;
}
这样就可以无刷新解决问题啦。