1官辈、頁(yè)面部分
引入的樣式溉知、js
jquery.fileupload.css
jquery-1.8.2.min.js
jquery.ui.widget.js
jquery.fileupload.js
頁(yè)面
<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 + "/";
// 為上傳的文件進(jìn)行重命名(避免同名文件的相互覆蓋)使用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();
}
//將臨時(shí)文件保存到磁盤
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 {
//校驗(yàn)類型
if (imageFile.getContentType().indexOf("image") == -1) {
throw new ServiceException("上傳失敗什湘,僅支持圖片類型埠通!");
}
if (imageFile.getSize() > (imageFileMaxSize * 1024 * 1024)) {
throw new ServiceException("上傳失敗赎离,文件大小不能超過(guò)" + imageFileMaxSize + "MB!");
}
}
}