代码已经上传至gitee
https://gitee.com/hashuaiboy/file-upload-demo
思路
使用 MultipartFile 文件类
String str = "E://images/";
@RequestMapping("/uploads")
public String FileUploads(HttpServletRequest request, MultipartFile file) {
String originalname = file.getOriginalFilename();
// 获取后缀
String newName = originalname.substring(originalname.lastIndexOf("."));
// 捕获后缀非jpg的文件
if (!".jpg".equals(newName)){
return "error";
}
newName = String.valueOf(new Random().nextInt(50)) + newName;
File newFile = new File(str, newName);
if (!newFile.getParentFile().exists()) {
newFile.getParentFile().mkdir();
}
try {
file.transferTo(newFile);
// save new upload file to database
files newfile = new files();
newfile.setFilename(newName);
newfile.setCreatetime(String.valueOf(new Date()));
fileService.save(newfile);
} catch (IllegalStateException | IOException exception) {
exception.printStackTrace();
}
return str + newName;
}
<el-upload
style="margin-top: 50px"
class="upload-demo"
ref="upload"
:on-preview="handlePictureCardPreview"
action="http://localhost:8081/api/uploads"
:on-success="handleSuccess"
:on-remove="handleRemove"
list-type="picture-card"
:file-list="fileList"
:on-exceed="handleExceed"
:auto-upload="false"
:multiple="false"
:limit="1"
:before-upload="beforeAvatarUpload"
>
<i class="el-icon-plus"></i>
</el-upload>
使用 Elementui 事半功倍
PS:图片文件会被存储到 E://images中
2 条评论
滴!学生卡!打卡时间:22:46:47,请上车的乘客系好安全带~