springboot+vue+mysql实现存储图片到数据库并显示
1.存储到数据库
(1)前端通过element ui 上传
<el-upload
class="avatar-uploader"
action="/api/setImage"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
>
<img v-if="imageUrl" :src="imageUrl" class="avatar" />
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
(2)后端
1.创建Picture实体类
@Entity
@Table(name = "picture")
public class Picture {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@Column(name = "name")
private String name;
@Column(name = "pic_data")
private byte[] pic_data;
@Column(name = "pid")
private int pid;
/** setter和getter方法 **/
}
2.Repository层
public interface PictureRepository extends JpaRepository<Picture,Integer>{
Picture findByPid(int pid);
}
- Service层
//保存头像
public void updateImg(MultipartFile multipartFile) throws IOException {
String name = multipartFile.getOriginalFilename();
byte[] bytes = multipartFile.getBytes();
Picture pic = new Picture();
pic.setPid(1);
pic.setName(name);
pic.setPic_data(bytes);
pictureRepository.save(pic);
}
4.Controller层
@RequestMapping(value = "/setImage")
public void getImage(@RequestParam(name = "file") MultipartFile file) throws IOException {
pictureService.updateImg(file);
System.out.println("success");
}
2.从数据库取出并显示到前端
(1)前端
<img :src="images" class="showavatar" />
this.$axios.get("/api/getImages", { responseType: "blob" }).then(res => {
let blob = new window.Blob([res.data]);
let url = window.URL.createObjectURL(blob);
this.images = url;
});
.showavatar {
border: 1px dashed #f50505;
border-radius: 50%;
width: 160px;
height: 160px;
background-size: 60px;
}
后端
1.Service层
//获取头像
public byte[] getImg() {
Picture p=pictureRepository.findByPid(1);
byte[] b=p.getPic_data();
return b;
}
2.controller层
@GetMapping(value="/getImages")
public byte[] getImg() {
byte[] b=pictureService.getImg();
return b;
}