vue+java通过blob实现图片预览功能

vue+java通过blob实现图片预览功能

vue部分

api

file.js

/**
 * 通过文件id获取文件路径
 */
export function getFilePath(c308Id) {
  return request({
    url: '/system/file/getFilePath/' + c308Id,
    method: 'get'
  })
}

element-ui

i21.vue

<imgappend disabled :ids='form.i21Id' table='i21' :auth='permission'  tips='' sizes='5000' types='jpg;png;' />


import imgappend from '@/views/components/imgappend'

imgappend.vue

<template>
  <div>
    {{ this.tips }}
    <el-upload
      :action="urls"
      list-type="picture-card"
      :file-list="appendfileList"
      :data="filedata"
      :disabled="flagedit"
      :headers="myHeaders"
      :on-success="handlesuccess"
      :on-preview="handlePictureCardPreview"
      :before-remove="handleRemove"
      :before-upload="handleUpload"
    >
      <i class="el-icon-plus">i>
    el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    el-dialog>
  div>
template>
<script>
import { getToken } from "@/utils/auth";
import { getFiles, delFile } from "@/api/tool/file";
import store from "@/store";
export default {
  data() {
    return {
      myHeaders: {},
      appendfileList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      filedata: {},
      flagedit: true,
      urls: "",
      baseU:'',
    };
  },
  methods: {
    delfile(file) {
      var _this = this;
      delFile(file.id).then((response) => {
        if (response.data == 1) {
          _this.appendfileList = _this.appendfileList.filter(
            (item) => item.id != file.id
          );
          return true;
        } else {
          _this.$alert(response.data.var_result, "删除失败", {
            confirmButtonText: "确定",
            type: "error",
          });
          return false;
        }
      });
    },
    handleUpload(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      var ext_type = true;
      var ext_size = true;
      if (typeof this.types !== "undefined") {
        ext_type = this.types.toLowerCase().indexOf(testmsg.toLowerCase()) >= 0;
      }

      const isLt2M = file.size / 1024;

      if (typeof this.sizes !== "undefined" && this.sizes !== "0") {
        ext_size = isLt2M <= Number(this.sizes);
      }

      if (!ext_type) {
        this.$message({
          message: "上传文件格式错误" + this.types,
          type: "warning",
        });
      }
      if (!ext_size) {
        this.$message({
          message: "上传文件大小不能超过" + this.sizes + "Kb",
          type: "warning",
        });
      }
      return ext_type && ext_size;
      //  return false;
    },

    handleRemove(file, fileList) {
      var _this = this;
      if (file.status !== "success") {
        return true;
      }
      _this
        .$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          _this.$options.methods.delfile.bind(_this)(file);
        })
        .catch(() => {});

      return false;
    },
    getfile() {
      var _this = this;
      getFiles({ idTable: this.table, idMain: this.ids }).then((response) => {
        var _this = this;
        _this.appendfileList = response.data;
        for (var i = 0; i < _this.appendfileList.length; i++) {
          _this.appendfileList[i].url = _this.baseU + _this.appendfileList[i].url;
        }
      });
    },
    handlesuccess(response, file, fileList) {
      this.appendfileList = fileList;
      file.id = response.msg;
      file.url = this.baseU + "/system/file/flowFile/file/" + file.id;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
  },
  props: ["ids", "table", "auth", "sizes", "tips", "types"],
  watch: {
    ids: function (newVal, oldVal) {
      this.urls =
        process.env.VUE_APP_BASE_API +
        "/system/file/uploadAccessory/" + this.ids + "/" + this.table;
      this.filedata.id = this.ids;
      this.filedata.table = this.table;
      var _this = this;
      _this.$options.methods.getfile.bind(_this)();
      if (this.auth.save) {
        this.flagedit = false;
      }
    },
  },
  created() {
    this.myHeaders = { Authorization: "Bearer " + getToken() };
    this.baseU = process.env.NODE_ENV === "production" ? "/ifs_avs" + process.env.VUE_APP_BASE_API : process.env.VUE_APP_BASE_API;
    if (this.ids != null) {
      this.filedata.id = this.ids;
      this.filedata.table = this.table;
      this.getfile();
      if (this.auth.save) {
        this.flagedit = false;
      }
    }

    //do something after creating vue instance
  },
};
script>

java部分

controller

@ApiOperation("车辆出入记录图片预览")
@GetMapping("/terminalImgFile/{i21Id}")
public AjaxResult terminalImgFile(@PathVariable("i21Id") String i21Id){
    // 获取文件路径集合
        List<String> filePathList = sys308Service.listFilePath("i21", i21Id);
        // 创建集合以保存blob数据
        List<String> base64List = new ArrayList<>();
        for (String filePath : filePathList) {
            try {
                // 找到文件
                File file = new File(filePath);
                // 转base64
                byte[] imageData = FileUtils.readFileToByteArray(file);
                String base64 = Base64.getEncoder().encodeToString(imageData);
                // 拼接格式
                base64 = "data:image/jpeg;base64," + base64;
                // 添加到集合
                base64List.add(base64);
            } catch (Exception e) {
                // 发生异常反馈前端
                throw new RuntimeException("图片预览数据转换异常");
            }
        }
        // 返回
        return AjaxResult.success("图片预览数据获取成功", base64List);
}

service

/**
 * 获取对应数据的附件地址
 * @param idTable
 * @param idMain
 * @return
 */
public List<String> listFilePath(String idTable, String idMain) {
   List<Sys308> files = sys308Mapper.getFiles(idTable, idMain);
   List<String> filePathList = new ArrayList<>();
   SysConfig sysConfig = configMapper.checkConfigKeyUnique("sys.file.basePath.profile");
   String basePath = sysConfig.getConfigValue();
   for (Sys308 file : files) {
       String filePath = basePath + file.getS308VarFilePath();
       filePath = filePath.replace("/profile/", "terminal");
       filePathList.add(filePath);
   }
   return filePathList;
}

mapper

sys308Mapper

// 根据主表简称、主表id获取到相关文件(集合)
List<Sys308> getFiles(@Param("idTable") String idTable, @Param("idMain") String idMain);

configMapper

/**
 * 根据键名查询参数配置信息
 * 
 * @param configKey 参数键名
 * @return 参数配置信息
 */
public SysConfig checkConfigKeyUnique(String configKey);

mapper.xml

sys308Mapper.xml

<resultMap id="BaseResultMap" type="com.rongyi.common.domain.Sys308">
	<id property="s308Id" column="s308_id" jdbcType="VARCHAR"/>
	...
resultMap>
<select id="getFiles" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List"/>
    from sys308
    where
    s308_id_table = #{idTable,jdbcType=VARCHAR}
    AND s308_id_main = #{idMain,jdbcType=VARCHAR} AND s308_flag_state = '9'
select>

configMapper.xml

<resultMap type="SysConfig" id="SysConfigResult">
	<id     property="configId"      column="config_id"      />
    <result property="configName"    column="config_name"    />
    <result property="configKey"     column="config_key"     />
    <result property="configValue"   column="config_value"   />
    <result property="configType"    column="config_type"    />
    <result property="createBy"      column="create_by"      />
    <result property="createTime"    column="create_time"    />
    <result property="updateBy"      column="update_by"      />
    <result property="updateTime"    column="update_time"    />
resultMap>
<select id="checkConfigKeyUnique" parameterType="String" resultMap="SysConfigResult">
    <include refid="selectConfigVo"/>
    where config_key = #{configKey} limit 1
select>

你可能感兴趣的:(项目框架学习,#,代码分享,Web项目技术,java,vue.js,javascript,若依,经验分享)