怎么预先在数据库存储图片路径,然后vue前端怎么接收springboot后端从数据库获取到的路径并显示图片
时间: 2024-06-09 12:10:58 浏览: 210
首先,在数据库中存储图片路径需要在后端进行操作。可以将图片存储在服务器上的某个文件夹中,并在数据库中存储该图片的路径,例如存储在路径为`/images`的文件夹中,则可以将图片路径存储为`/images/xxx.jpg`。
接下来,后端可以通过接口将存储在数据库中的图片路径返回给前端。在Spring Boot中,可以使用`@RestController`注解定义一个RESTful接口,使用`@GetMapping`注解定义一个GET请求的接口,然后使用`ResponseEntity`将图片返回给前端,例如:
```java
@RestController
public class ImageController {
@GetMapping("/image/{id}")
public ResponseEntity<byte[]> getImage(@PathVariable("id") Long id) throws IOException {
// 根据id从数据库中获取图片路径
String imagePath = getImagePathById(id);
// 读取图片文件
File file = new File(imagePath);
FileInputStream input = new FileInputStream(file);
byte[] bytes = new byte[input.available()];
input.read(bytes);
input.close();
// 设置HTTP响应头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG);
// 返回图片数据
return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
}
// 根据id从数据库中获取图片路径的实现代码
private String getImagePathById(Long id) {
// ...
}
}
```
在Vue前端中,可以使用`<img>`标签来显示图片。在`src`属性中设置图片的URL,即可从后端获取图片并显示,例如:
```html
<template>
<div>
<img :src="imageSrc" alt="image">
</div>
</template>
<script>
export default {
data() {
return {
imageSrc: ''
}
},
mounted() {
this.loadImage()
},
methods: {
loadImage() {
// 发送GET请求获取图片数据
axios.get('/image/1', {
responseType: 'arraybuffer'
}).then(response => {
// 将图片数据转换为Base64编码的字符串
let base64Str = btoa(
new Uint8Array(response.data)
.reduce((data, byte) => data + String.fromCharCode(byte), '')
)
// 设置图片的URL
this.imageSrc = 'data:image/jpeg;base64,' + base64Str
})
}
}
}
</script>
```
这样,前端就可以从后端获取存储在数据库中的图片并显示了。
阅读全文