第一次写前后端图片类型文件交互,踩了很多坑,查了好多文章才解决,怕自己忘记,写篇文章记一下。
上传图片至后端,并存储:
前端:
页面中用<el-upload>
<el-upload :action="updateurl"
:show-file-list="false"
:before-upload="beforeImgUpload"
:http-request="onUpload">
<el-button>更新图片</el-button>
</el-upload>
ts方法: 要注意headers,一开始没配置headers跨域一直报错
onUpload (file) {
let formData = new FormData()
formData.append('file',file.file);
axios({
url:'/Position/updateMap',
method: 'post',
data:formData,
headers: {
'Content-Type': 'multipart/form-data'
}
})
}
后端:
用MultiparFile类接收
@PostMapping("/Position/updateMap")
public R updateMap(@RequestParam(value = "file") MultipartFile urlFile){
return positionService.updateMap(urlFile);
}
具体存储逻辑
一开始用相对路径,存了但是读取的时候找不到,干脆直接System.getProperty("user.dir")了
public R updateMap(MultipartFile urlFile) {
String fileName = "parking.png";
String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "img" ;
File file1 = new File(filePath);
if (!file1.exists()) {
if (!file1.mkdir()) {
return R.fatal("创建文件夹失败");
}
}
File dest = new File(filePath + System.getProperty("file.separator") + fileName);
String storeUrlPath = "/img/map/" + fileName;
try {
urlFile.transferTo(dest);
return R.success("上传成功");
} catch (IOException e) {
return R.fatal("上传失败" + e.getMessage());
}
}
读取
一开始想直接传url直接读,一开始可以,但改了下代码后url正确前端却总是404。参考:https://blog.csdn.net/2301_76212351/article/details/136037661后发现还是要用流传输。
前端:
axios设置返回值类型为blob,在用createObjectURL创建图片链接,后面哪里要用这个图片就用在src处用mapurl。
const mapurl:any = ref(0);
axios.get("后端接口",{
responseType: 'blob',//设置返回类型
}).then((res)=>{
try {
let blob = new Blob([res.data]);
// 兼容不同浏览器的URL对象
const url = window.URL || window.webkitURL;
mapurl.value=url.createObjectURL(blob);
}catch (e) {
console.log('下载的图片出错',e)
}
})
例子:
<img :src=mapurl style="height: 100%;width: 100%">
后端:
一开始用相对路径,总是读不到文件,搞的read报错,用System.getProperty("user.dir")就好了,也不知道为啥。
public ResponseEntity<InputStreamResource> getMap( ) {
String fileName = "parking.png";
String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "img"+System.getProperty("file.separator") ;
String imageFilePath = filePath+fileName;
File file = new File(imageFilePath);
try {
BufferedImage bufferedImage = ImageIO.read(file);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", byteArrayOutputStream);
byte[] imageBytes = byteArrayOutputStream.toByteArray(); // 读取图片数据的字节数组
InputStream inputStream = new ByteArrayInputStream(imageBytes);
// 创建InputStreamResource对象,该对象将用作响应体
InputStreamResource resource = new InputStreamResource(inputStream);
// 创建包含响应体的ResponseEntity对象,并设置正确的媒体类型和内容长度
inputStream.close();
byteArrayOutputStream.flush();
byteArrayOutputStream.close();
return ResponseEntity.ok()
.contentType(MediaType.IMAGE_JPEG)
.header("Content-Disposition\", \"inline; filename=image.jpg")
.body(resource);
}catch (Exception e) {
e.printStackTrace();
}
return ResponseEntity.ok().body(null);
}
小白选手,有什么错误还请各位大佬指正