Springboot与前端图片交互(二)

Springboot与前端图片交互(二)

开发需求:将文件的地址放到数据库中

前面我用的是直接在在磁盘中进行存储,没有和数据库进行交互。如果文件直接在磁盘上存储,当存储量较大的时候往往会造成资源混乱,不容易管理。因此可以采用将文件放入到磁盘中,将文件的地址放入到数据库中,访问文件的时候只需要从数据库中拿到地址就可以访问。

前端和Springboot与前端图片交互(一)一样

服务端

为了方便起见,我这里还是以图片为例,数据库采用mysql

1.导入maven依赖

<!--mysql驱动-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!--mybatis启动器-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
2.连接数据库
server.port=8886
spring.datasource.url=
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

3.编写业务层

Controller层

  1. 通过@RequestParam MultipartFile file获取前端传过来的图片
  2. 将文件名通过uuid进行从命名,避免重名
  3. 通过输入输出流存储到电脑硬盘
  4. 通过数据库存储业务将文件名和路径写入到数据库中
@Autowired
PicService picService;
@PostMapping(value = "/postpicpath")
private void upLoadName(@RequestParam MultipartFile file) throws IOException {
    String name =file.getOriginalFilename();
    String type = name.substring(name.lastIndexOf("."));
    UUID uuid = UUID.randomUUID();
    FileOutputStream fileOutputStream = new FileOutputStream("J:\\springboot_data\\" + uuid.toString()+ type);
    fileOutputStream.write(file.getBytes());
    fileOutputStream.close();
    Picpath picpath = new Picpath();
    picpath.setName(name);
    picpath.setUuid(uuid.toString());
    picService.PicpathService(picpath);
}

picPath实体类:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Picpath {
    private int id;
    private String name;
    private String uuid;
}

dao层:

@Insert("INSERT INTO loveweb.picpath (name,uuid) values(#{name},#{uuid});")
int add(Picpath picpath);

service 层:

int PicpathService(Picpath picpath);

@Resource
PicDao picDao;
@Override
public int PicpathService(Picpath picpath) {
    return picDao.add(picpath);
}

图片获取:

controller层:

  1. 可以通过返回字节写入到body中
@GetMapping("/getpicpath/{id}")
@ResponseBody
private byte[] getPicName(@PathVariable("id") int id) throws IOException {
    Picpath picPath = picService.getPicPathService(id);
    String name = picPath.getName();
    String type = name.substring(name.lastIndexOf("."));
    String uuid = picPath.getUuid();
    FileInputStream picInput = new FileInputStream("J:\\springboot_data\\" + uuid+ type);
    return picInput.readAllBytes();
}
  1. 可以通过Response设置响应头和响应体,当前端访问接口,可以实现文件下载
@GetMapping("/download/{id}")
private void picDownload(@PathVariable("id") int id,HttpServletResponse httpServletResponse) throws IOException {
    Picpath picPath = picService.getPicPathService(id);
    String name = picPath.getName();
    String type = name.substring(name.lastIndexOf("."));
    String uuid = picPath.getUuid();
    FileInputStream picInput = new FileInputStream("J:\\springboot_data\\" + uuid+ type);

    //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
    httpServletResponse.setContentType("multipart/form-data");
    //2.设置文件头:最后一个参数是设置下载文件名(假如我们叫a.pdf)
    httpServletResponse.setHeader("Content-Disposition", "attachment;fileName="+name);
    //3.通过response获取ServletOutputStream对象(out)
    ServletOutputStream outputStream = httpServletResponse.getOutputStream();
    int b = 0;
    byte[] buffer = new byte[512];
    while (b != -1){
        b = picInput.read(buffer);
        //4.写到输出流(out)中
        outputStream.write(buffer,0,b);
    }
    picInput.close();
    outputStream.close();
    outputStream.flush();
    System.out.println("成功");
}

dao层:

@Select("SELECT * FROM loveweb.picpath WHERE id = #{id};")
Picpath getPicPath(int id);

service层:

Picpath getPicPathService(int id);

@Override
public Picpath getPicPathService(int id) {
    return picDao.getPicPath(id);
}

前端实现:

<template>
  <div>
    <el-upload action="http://localhost:8887/postpicpath">
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>
    <el-button @click="btn">显示</el-button>
    <a href="http://localhost:8887/download/1">下载</a>
    <br>
    <el-image :src="src"></el-image>
  </div>
</template>

<script>
  import Axios from 'axios';
  export default {
    name: 'path',
    data () {
      return {
        src:''
      }
    },
    methods:{
      async btn(){
        const res = await Axios({url:"http://localhost:8887/getpicpath/1",method:'get',responseType:'blob'})
        let blob = new window.Blob([res.data]);
        let url = window.URL.createObjectURL(blob);
        this.src = url;
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

演示:
上传:

在这里插入图片描述

在磁盘中存储:
在这里插入图片描述

数据库:
在这里插入图片描述

显示:

在这里插入图片描述

下载:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值