1、upload.html中上传组件
<el-upload class="avatar-uploader"
action="/common/upload"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeUpload"
ref="upload">
<img v-if="imageUrl" :src="imageUrl" class="avatar"></img>
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<script>
new Vue({
el: '#food-add-app',
data() {
return {
imageUrl: ''
}
},
methods: {
handleAvatarSuccess (response, file, fileList) {
this.imageUrl = `/common/download?name=${response.data}`
},
beforeUpload (file) {
if(file){
const suffix = file.name.split('.')[1]
const size = file.size / 1024 / 1024 < 2
if(['png','jpeg','jpg'].indexOf(suffix) < 0){
this.$message.error('上传图片只支持 png、jpeg、jpg 格式!')
this.$refs.upload.clearFiles()
return false
}
if(!size){
this.$message.error('上传文件大小不能超过 2MB!')
return false
}
return file
}
}
}
})
</script>
2、Controlller
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
@Value("${file-upload.address}")
private String fileAddress;
@PostMapping("/upload")
public R load(MultipartFile file) throws IOException {
log.info("图片上传...");
File f = new File(fileAddress);
if(!f.exists()){
f.mkdirs();
}
//截取图片后缀名
String fileSuffer = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
// 生成的uuid+当前时间戳+图片后缀 = 图片名
String fileName = UUID.randomUUID().toString() + System.currentTimeMillis() + fileSuffer;
// 储存到电脑路径
file.transferTo(new File(fileAddress + fileName));
return R.success(fileName);
}
@GetMapping("/download")
public void download(String name, HttpServletResponse response){
try {
FileInputStream fileInputStream = new FileInputStream(new File(fileAddress + name));
ServletOutputStream outputStream = response.getOutputStream();
int len = 0;
byte[] bytes = new byte[1024];
while ((len = fileInputStream.read(bytes)) != -1){
outputStream.write(bytes,0,len);
outputStream.flush();
}
outputStream.close();
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
3、application.yml
file-upload:
address: E:\code\workspace\upload\