基于若依VUE实现图片上传保存到数据库和下载预览功能

程彭祖
2023-12-01

图片上传

前台代码

上传图片表单部分

<el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" enctype="multipart/form-data">
        
      
       <el-form-item label="文件" prop="file">
        <img :src="form.data" style="width:50%;height:50%"  >
          <input type="file" id="file_input" >
     
        </el-form-item>  
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
        <el-button @click="downloadfile">下载</el-button>
      </div>
    </el-dialog>
表单提交方法中获取file对象并放入formData 中传到后台
var formData = new FormData();
             formData.append('file', document.getElementById('file_input').files[0]);
            addBin(formData).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
// 新增
export function addBin(data) {
  console.log(data.file)
  return request({
    url: '/system/bin',
    method: 'post',
    data: data
  })
}

后台代码

获取mysql数据库链接,调用执行insert方法

public Connection getConnection() throws Exception{



        String url = "jdbc:mysql://***.***.**.***:3306/***?characterEncoding=utf-8&serverTimezone=UTC";

        String user = "**";

        String password = "**";

        Class.forName("com.mysql.cj.jdbc.Driver");

        Connection conn = DriverManager.getConnection(url, user, password);

        return conn;

    }
    //增加图片
    public void save(File file) throws Exception{

        Connection conn = getConnection();

        String sql = "insert into tab_bin (filename,data) values(?,?)";

        PreparedStatement prest = conn.prepareStatement(sql);
        String filename=file.getName();
        prest.setString(1, filename);/
        FileInputStream fis = new FileInputStream(file);
        prest.setBlob(2, fis,file.length());
        prest.execute();   //执行
        if(prest!=null){
            prest.close();
        }
        if(conn!=null){
            conn.close();
        }

    }

接收方法,调用上一步插入图片插入成功

/**
     * 新增文件
     */
    @PreAuthorize("@ss.hasPermi('system:bin:add')")
    @Log(title = "文件", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add( @RequestParam("file") MultipartFile file) throws Exception {
        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        save(toFile);
        return toAjax(1);
    }
      //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

图片下载

前台下载方法,传入文件名

 //文件下载
    downloadfile(){
      this.queryParams.filename=this.form.filename;
       const queryParams = this.queryParams;

  this.$confirm('是否确认下载?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return downloadBin(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
 
    },

后台下载方法


   /**
     * 下载文件
     */
    @GetMapping("/download")
    public AjaxResult download(TabBin tabBin) throws Exception {
        Connection conn = getConnection();
        System.out.print("1");
        String filename=tabBin.getFilename();
        String sql = "select * from tab_bin where filename= '"+filename+"'";
        PreparedStatement prest = conn.prepareStatement(sql);

        ResultSet rs = prest.executeQuery();
        OutputStream out = null;
        while(rs.next()){
            Blob bl = rs.getBlob("data"); 
            InputStream is = bl.getBinaryStream();  //查看blob,可以通过流的形式取出来。
            BufferedInputStream buffis = new BufferedInputStream(is);
            //保存到buffout,就工程目录下的filename的文件

            BufferedOutputStream buffout = new BufferedOutputStream( new FileOutputStream(getAbsoluteFile(filename)));
            byte[] buf= new byte[1024];
            int len = buffis.read(buf, 0, 1024);
            while(len>0){
                buffout.write(buf);
                len=buffis.read(buf, 0, 1024);
            }
            buffout.flush();
            buffout.close();
            buffis.close();
        }
        if(prest!=null){
            prest.close();
        }
        if(conn!=null){
            conn.close();
        }
        return AjaxResult.success(filename);
    }

图片预览

前台打开修改界面时,提前调用查询图片方法,传入文件名

/** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getBin(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改文件";



        this.queryParams.filename=this.form.filename;
        const queryParams = this.queryParams;
        updownload(queryParams).then(response => {
        console.log(response);
        //增加判断
        if(this.queryParams.filename.indexOf(".png") != -1){
          this.form.data='data:image/png;base64,'+response.msg;
        }else if(this.queryParams.filename.indexOf(".jpg") != -1){
          this.form.data='data:image/jpg;base64,'+response.msg;
        }
       
        })
       

      });
    },

后台返回转好的base64码,注意图片格式。这里我只用了png和jpg

@GetMapping("/updownload")
    public AjaxResult updownload(TabBin tabBin) throws Exception {
        Connection conn = getConnection();
        System.out.print("1");
        String filename=tabBin.getFilename();
        String sql = "select * from tab_bin where filename= '"+filename+"'";
        PreparedStatement prest = conn.prepareStatement(sql);

        ResultSet rs = prest.executeQuery();
        OutputStream out = null;
        String result="";
        while(rs.next()){
            Blob realBlob = rs.getBlob("data");
            // 创建byte数组输出对象
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            // 创建一个长度为100的byte数组
            byte[] buff = new byte[100];
            int rc = 0;
            // 获取BLOB数据对象的二进制流
            InputStream binaryStream = realBlob.getBinaryStream();
            while ((rc = binaryStream.read(buff, 0, 100)) > 0) {
                byteArrayOutputStream.write(buff, 0, rc);
            }
            byte[] byteArray = byteArrayOutputStream.toByteArray();
            result = Base64.getEncoder().encodeToString(byteArray);

        }
        if(prest!=null){
            prest.close();
        }
        if(conn!=null){
            conn.close();
        }
        return AjaxResult.success(result);
    }

前台显示,主要是img标签src绑定值替换为后台传过来的base64编码即可达成预览效果。

 <img :src="form.data" style="width:50%;height:50%"  >
 类似资料: