首页 > 其他分享 >vue2 上传图片

vue2 上传图片

时间:2024-03-19 11:00:29浏览次数:12  
标签:vue2 res publicjs fileList String file 上传 id 图片

一、前端

      <el-row>
              <el-form-item label="上传文件" props="fileList">
                <el-upload
                  ref="upload"
                  action="#"
                  list-type="picture-card"
                  multiple 
                  accept="image/jpeg, image/jpg, image/png,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/pdf,application/msword"
                  :file-list="fileList"
                  :auto-upload="false"
                  :on-change="handleChange"
                  :on-remove="handleRemove"
                  :on-preview="handlePreview"
                  >
                  <i slot="default" class="el-icon-plus" ></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                  <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
              </el-form-item>
            </el-row>

二、逻辑,判断文件大小以及重复图片校验

    uploadImageSize(that, file, fileList) {
        if (file.size / 1024 / 1024 > 10) {
            publicJS.showMessage("单个文件大小不能超过10MB", publicJS.ErrorType);
            let index = that.fileList.indexOf(file)   //删除超过10M的照片
            that.fileList = fileList;
            if (index > -1) {
                that.fileList.splice(index, 1)
            }
        } else {
            let newArr = fileList.filter(item => item.name == file.name)
            let count = newArr.length;
             //删除重复数据
            if(count > 1){
                let index = fileList.indexOf(file)  
                if (index > -1) {
                    publicJS.showMessage("文件"+file.name+"已存在!", publicJS.ErrorType);
                    fileList.splice(index, 1)
                }
            }
            that.fileList = fileList;
        }
    },

  三、方法

   // 判断文件的大小不超过10m,判重
    handleChange(file,fileList){
      this.$publicjs.uploadImageSize(this,file,fileList)
    },
    // 删除文件
    handleRemove(file,fileList) {
      this.fileList = fileList;
      if(file.id){
        this.$confirm("确定要删除此文件吗,删除后不可恢复。",'提示',{
            confirmButtonText:'确定',
            cancelButtonText:'取消',
            type:'warning'
        }).then(()=>{
          deleteItemImg(file.id).then(res =>{
            if(res.code==200){
            this.$publicjs.showMessage(res.message, this.$publicjs.SuccessType);
            }else{
              this.fileList.push(file);
             this.$publicjs.showMessage(res.message, this.$publicjs.ErrorType);
            }
          })
        }).catch(()=>{
          this.fileList.push(file);
        })
      }
    },
    // 预览图片
    handlePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },

  四、带着图片一起保存

 
 saveMethod() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 文件内容
          let saveData = new FormData();
          for (let i = 0; i < this.fileList.length; i++) {
            if (this.fileList[i].raw) {
              saveData.append("file", this.fileList[i].raw);
            }
          }
          for(let x in this.form){
            if(this.form[x] != ""){
              saveData.append(x,this.form[x]);
            }
          }
          if (this.form.id == "") {
            addData(saveData).then((res) => {
              if (res.code == 200) {
                this.$publicjs.showMessage(res.message, this.$publicjs.SuccessType);
                this.queryMethod();
                this.isShowTable = true;
                this.isShowOrgTree = true;
              } else {
                this.$publicjs.showMessage(res.message, this.$publicjs.ErrorType);
              }
            });
          } else {
            updateData(saveData).then((res) => {
              if (res.code == 200) {
                this.$publicjs.showMessage(res.message, this.$publicjs.SuccessType);
                this.queryMethod();
                this.isShowTable = true;
                this.isShowOrgTree = true;
              } else {
                this.$publicjs.showMessage(res.message, this.$publicjs.ErrorType);
              }
            });
          }
          this.fileList=[];
        }
      });
    },

五、调用后端接口方法

// 物品上传图片
export function getItemFile(params) {
  return request({
    url: 'api/sys-attach-filepath-info/query',
    method: 'get',
    params
  })
}
// 删除单个物品图片
export function deleteItemImg(id) {
  return request({
    url: 'api/sys-attach-filepath-info/' + id,
    method: 'delete'
  })
}
// 添加
export function addData(data) {   return request({     url: 'api/sys-case-info/add',     method: 'post',     data   }) } // 更新
export function updateData(data) {   return request({     url: 'api/sys-case-info',     method: 'put',     data   }) }
 

六、后端接口--控制器

1、@ApiOperation(value = "查询分页数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageIndex", value = "页码"),
            @ApiImplicitParam(name = "pageCount", value = "每页条数"),
            @ApiImplicitParam(name = "relationId", value = "相关数据id")
    })
    @GetMapping(value = "/query")
    public Response<String> findListByPage(@RequestParam(value = "page_index", required = false) Integer pageIndex,
                                           @RequestParam(value = "page_count") Integer pageCount,
                                           String relationId){}
2、删除图片

@ApiOperation(value = "删除")
@DeleteMapping("{id}")
public Response<Integer> delete(@PathVariable("id") String id){
int re = sysAttachFilepathInfoService.delete(id);
if (re > 0) {
return new Response<>(ErrorCode.SUCESS_CODE, "删除成功", re);
} else {
return new Response<>(ErrorCode.INTERNAL, "删除失败,未知错误", null);
}
}
3、保存
@ApiOperation(value = "新增")
@PostMapping(value = "/add")
public Response<Integer> add(SysCaseInfo sysCaseInfo,@RequestParam("file") MultipartFile[] files){}
4、更新
@ApiOperation(value = "更新")
@PutMapping()
public Response<Integer> update(SysCaseInfo sysCaseInfo,@RequestParam("file") MultipartFile[] files){}

七、后端接口-实现类

一、文件路径
public static String fileUpload(MultipartFile[] files, String id, String path,String tableName) {
String thumn = "";
try {
if (files != null && files.length > 0) {
File filePath = new File(path+tableName);
//判断filePath是否存在
if (!filePath.exists() && !filePath.isDirectory()) {
//filePath目录不存在,需要创建
filePath.mkdirs();
}
int len = files.length;
for (int i = 0; i < len; i++) {
//获取文件原始名称(带扩展名)
String originalFilename = files[i].getOriginalFilename();
//获取文件类型
String type = originalFilename.substring(originalFilename.lastIndexOf("."));
//生成新文件名称
String filename =tableName+"/"+ id + "_" + System.currentTimeMillis() + type;
byte[] bytes = files[i].getBytes();
File file1 = new File(path + filename);
if (file1.exists() && !file1.delete()) {
throw new Exception((path + filename) + "文件删除错误");
}
Path newpath = Paths.get(path + filename);
Files.write(newpath, bytes);
if (i < len - 1) {
thumn += filename + ",";
} else {
thumn += filename;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return thumn;
}
二、添加文件保存在表中
 public void addFile(MultipartFile[] files, String id, String tableName) {
        // 图片列表
        List<SysAttachFilepathInfo> fileList = new ArrayList<>();
        //存储图片的路径
        int count = files.length;
        if (files != null && count > 0) {
            String path = fileConfig.getFileServer();
            String filepaths = FileUtil.fileUpload(files, id, path,tableName);   //上传图片
            String[] filepath = filepaths.split(",");
            for(int i = 0; i < filepath.length; i++){
                SysAttachFilepathInfo info = new SysAttachFilepathInfo();
                info.setId(SnowIdUtil.getId());
                // 关联主键
                info.setRelationId(id);
                // 关联表
                info.setRelationTable(tableName);
                // 图片路径
                info.setFilePath(filepath[i]);
                fileList.add(info);
            }
            // 如果有数据则保存
            if(CollectionUtils.isNotEmpty(fileList)){
                sysAttachFilepathInfoMapper.batchInsert(fileList);
            }
        }
    }

八、批量操作 xml文件

    一、批量添加
    <insert id="batchInsert" parameterType="com.hengan.involved.entity.SysAttachFilepathInfo">
        INSERT INTO sys_attach_filepath_info (id, relation_table, relation_id,file_path) values
        <foreach collection="list" item="item" separator=",">
            (#{item.id}, #{item.relationTable}, #{item.relationId}, #{item.filePath})
        </foreach>
    </insert>
二、批量更新
<update id="batchUpdate" parameterType="java.util.List">
<foreach collection="list" item="item" index="index" separator=";">
UPDATE show_overview set item_num = #{item.itemNum} WHERE id=#{item.id}
</foreach>
</update>
 

 

 

 

标签:vue2,res,publicjs,fileList,String,file,上传,id,图片
From: https://www.cnblogs.com/flyShare/p/18082232

相关文章

  • vue2结合element UI组件库封装的搜索组件
    可以根据不同的搜索条件自动排版,分为一个搜索条件,2-4个搜索条件,大于5的搜索条件具体样例见下方 封装的组件库:el-seacher.vue<template> <divv-if="!isModalSearch"class="searchFormborder-basic":class="isHeaderSearch?'headerBack':'whiteBtnBgd'&q......
  • 【matlab】如何批量修改图片命名
    【matlab】如何批量修改图片命名(●’◡’●)先赞后看养成习惯......
  • Vue2(五):收集表单数据、过滤器、自定义指令、Vue的生命周期
    一、收集表单数据爱好:学习<inputtype="checkbox"value="study"v-model="hobby">打游戏<inputtype="checkbox"value="games"v-model="hobby">吃饭<inputtype="checkbo......
  • NCV7321D11R2G收发器中文资料PDF数据手册引脚图参数图片价格芯片概述特性原理
    产品概述:NCV7321是一款全功能局部互联网(LIN)收发器,适用于LIN协议控制器和物理总线之间的接口。该收发器以I3T技术实施,可实现高电压模拟电路和数字功能在同一个芯片上的共存。NCV7321LIN器件属于车内联网(IVN)收发器系列。LIN总线适用于以最低可能成本从控制设备......
  • 用友U8 CRM客户关系管理系统 getemaildata.php 任意文件读取漏洞&任意文件上传漏洞
    漏洞简介用友U8CRM客户管理系统getemaildata.php存在任意文件读取漏洞,攻击者通过漏洞可以获取到服务器中的敏感文件。用友U8CRM客户关系管理系统getemaildata.php文件存在任意文件上传漏洞,攻击者通过漏洞可以获取服务器权限。Fofa:body="用友U8CRM"登录界面文件上传漏洞复......
  • EasyExcel实现文件上传下载(百万级数据、单元格自定义样式)
    文章目录一、EasyExcel介绍二、写Excel1、最简单的写2、列宽、行高、背景颜色、字体大小颜色、对齐方式2.1、编码方式2.2、注解方式3、复杂头与修改列顺序4、日期、数字类型和自定义格式化5、设置单元格下拉6、重复多次写入(百万数据)7、导出指定列8、动态生成表头9、模......
  • vue面试题(vue2响应式源码剖析)
    一、前言这篇文章结合Vue2.7.16的源码和一个Vue2的项目,来详细讲解Vue2实现响应式数据的核心代码1.1准备安装@vue/clinpminstall-g@vue/cli创建vue项目vuecreatevue2-test修改Vue实例的配置对象二、响应式处理的入口通过newVue()调用Vue构造函数,......
  • vue面试题(vue2响应式数据基础)
    一、什么是响应式数据响应式数据是指当数据发生变化时,相关的视图或组件会自动更新,保持与数据的同步。这样的设计使得开发者能够更方便地管理和更新数据,无需手动操作DOM或显式地更新视图。当数据发生变化时,所有使用该数据的地方都会自动更新。二、观察者模式观察者模式定义对......
  • 本地mysql测试成功后上传至云服务器出现了这么多问题?
    本地MySQL数据库迁移至云服务器的过程中可能出现多种问题,以下是常见的一些原因及其解决思路:权限问题:账户权限:本地MySQL数据库的用户权限设置可能与云服务器上的MySQL实例不同,比如未授权远程连接或赋予了错误的权限。你需要确认云服务器MySQL数据库的用户是否有从远程IP......
  • 前端面试题-vue2和vue3的区别
    监测机制的改变vue2对数据监测使用的是Object.definePropert()对数据进行劫持,结合发布订阅者模式来实现vue3通过使用proxyAPI对数据直接进行代理。vue3优于vue3的的地方就是:vue3的proxyAPI监测的是整个对象,而不再是某个属性消除了Vue2当中基于Object.defineProperty......