springboot+vue+mysql实现存储图片到数据库并显示

springboot+vue+mysql实现存储图片到数据库并显示,第1张

springboot+vue+mysql实现存储图片数据库并显示

springboot+vue+mysql实现存储图片到数据库并显示

1.存储到数据库

(1)前端通过element ui 上传(2)后端 2.从数据库取出并显示到前端

(1)前端后端PS:一般图片是不会存到数据库的,而是存到服务器上,数据库保存的是图片路径。

1.存储到数据库 (1)前端通过element ui 上传
 
            
            
          
(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;
	   
}

2.Repository层

public interface PictureRepository extends JpaRepository{
    
	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)前端
  
  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;
	}

PS:一般图片是不会存到数据库的,而是存到服务器上,数据库保存的是图片路径。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5717875.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存