1、页面部分
引入的样式、js
jquery.fileupload.css
jquery-1.8.2.min.js
jquery.ui.widget.js
jquery.fileupload.js
页面
<div class="btn btn-primary btn-sm fileinput-button" id="hide-button">
<i class="glyphicon glyphicon-plus"></i>
<span>上传</span>
<input id="imageFile" type="file" name="imageFile">
</div>
绑定事件
$('#' + fileId).fileupload({
url: '/upload/image?type=' + type,
add: function (e, data) {
var uploadErrors = [];
var acceptFileTypes = /^image\/(png|jpe?g)$/i;
//文件类型判断
if (!acceptFileTypes.test(data.originalFiles[0]['type'])) {
return false;
}
//文件大小判断
if (data.originalFiles[0]['size'] > 5000 * 1024) {
return false;
}
if (uploadErrors.length > 0) {
return false;
} else {
data.submit();
}
},
done: function (e, data) {
......
}
});
2、java部分
@RestController
@RequestMapping("/file")
public class FileController {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Value("${app.file.upload.server.origin}")
private String origin;
@Value("${app.file.upload.server.path}")
private String realPath;
@Value("${app.file.upload.dir.userPicture}")
private String userPicturePath;
@Value("${app.file.upload.size.max.image}")
private int imageFileMaxSize;
@PostMapping("/upload/image")
public Result uploadImage(@RequestParam MultipartFile imageFile) {
validateImageFile(imageFile);
String dateDIR = DateFormatUtils.format(new Date(), "yyyyMMdd");
String path = userPicturePath + dateDIR + "/";
// 为上传的文件进行重命名(避免同名文件的相互覆盖)使用UUID + 文件后缀
String suffix = imageFile.getOriginalFilename().substring(imageFile.getOriginalFilename().lastIndexOf("."));
String fileName = UUID.randomUUID().toString() + suffix;
File file = new File(realPath + path + fileName);
if (!file.getParentFile().exists()) {
file.mkdirs();
}
//将临时文件保存到磁盘
try {
imageFile.transferTo(file);
} catch (IOException e) {
logger.error("文件上传失败", e);
throw new ServiceException("上传失败:" + e.getMessage());
}
Map<Object, Object> data = Maps.newLinkedHashMap();
data.put("url", origin + path + fileName);
return ResultGenerator.genSuccessResult(data);
}
private void validateImageFile(MultipartFile imageFile) throws ServiceException {
//校验类型
if (imageFile.getContentType().indexOf("image") == -1) {
throw new ServiceException("上传失败,仅支持图片类型!");
}
if (imageFile.getSize() > (imageFileMaxSize * 1024 * 1024)) {
throw new ServiceException("上传失败,文件大小不能超过" + imageFileMaxSize + "MB!");
}
}
}
网友评论