Vue之多图上传

最近做的项目涉及到了上传多张图片,基本功能都实现了,能添加多张图片,也能编辑删除图片,但是上传的时候,每次点加号,在文件中选中图片后,渲染的时候总是重复刷新一下。

组件 MultiUpload.vue 如下:

<template>
  <div>
    <el-upload class="uploader" :headers="authorToken" :action="UPLOAD_URL" :auto-upload="true"
               :file-list="fileList" list-type="picture-card" :limit="limit?limit:9" :accept="fileType?fileType:'image/*'"
               :on-success="handleGoodsImagesUploadSuccess" :before-upload="handlebeforeUpload" :multiple="true"
               ref="fileupload" :on-exceed="handleUploadExceed" :on-remove="handleRemove"
               :on-preview="handlePictureCardPreview">
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :append-to-body="true" :visible.sync="dialogImgVisible" style="z-index: 3000;text-align: center;"
               :close-on-click-modal="false" :close-on-press-escape="false" custom-class="pub_dialog">
      <img width="80%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<!--
	使用用例
	fileType可以是
	audio/*表示“任何音频文件
	video/*表示“任何视频文件
	image/*表示“任何图像文件
	还可以以逗号拼接,如image/*,.pdf

	<multi-upload v-model="form.voucherUrlList" :fileType="image/*"></multi-upload>

	import MultiUpload from '@/components/Upload/MultiUpload'

	components: {
		MultiUpload
	},
-->


<script>
// import {
// 	UPLOAD_URL
// } from '../../utils/api.js';
export default {
  props: {
    value: {
      type: Array,
      default: () => []
    },
    limit: {
      type: Number,
      default: 9
    },
    fileType: String,
  },
  data() {
    return {
      authorToken: {
        'Authorization': 'Bearer ' + sessionStorage.getItem("token")
      },
      UPLOAD_URL: "/v1/admin/common/upload", // 上传的图片服务器地址 即上传图片后台接口的路径
      loading: '',
      param: {
        token: ''
      },
      dialogImageUrl: "",
      dialogImgVisible: false,
      disabled: false,
      imgs:[],
      num:0,
      fileNum:0
    }
  },
  computed: {
    // ['xxx', 'xxx'] 转换为 [{url: 'xxx'}, {url: 'xxx'}]
    fileList() {
      return this.value.map(url => ({
        url
      }))
    }
  },
  methods: {
    handlePictureCardPreview: function(file) {
      this.dialogImageUrl = file.url;
      this.dialogImgVisible = true;
    },
    handleRemove: function(file, fileList) {
      // fileList 为删除后的文件列表
      const value = fileList.map(v => v.url)
      this.$emit('input', value)
    },
    handleGoodsImagesUploadSuccess(response, file, fileList) {
      console.log(response);
      console.log(fileList);

      if (response.code == 200) {
        let imageUrl = response.data;
        this.imgs.push(imageUrl);
        this.num++;
        if(this.num == this.fileNum){
          this.num = 0;
          this.fileNum = 0;
          // 这里如果 this.value.push(imageUrl) 这么写,vue会报出警告,大概意思是value作为props不应该在子组件中被修改
          // 应该根据 value 得到新的值,而不能修改它,this.value.concat(imageUrl)也是可以的,concat方法返回新的数组
          // this.$emit('input', [...this.value, imageUrl])
          this.$emit('input', this.value.concat(this.imgs))
          this.imgs =[];
        }
      } else {
        this.$message.error(file.name + '上传失败!');
      }
    },
    handlebeforeUpload(file) {
      // 这里做可以做文件校验操作
      const isImg = /^image\/\w+$/i.test(file.type)
      if (!isImg && this.fileType == 'image/*') {
        this.$message.error('只能上传 JPG、PNG、GIF 格式!')
        return false
      }
      this.fileNum++;
      console.log(this.fileNum);
    },
    handleUploadExceed() {
      this.$message.error(`最多上传${this.limit}张图片`)
    },
  }
}
</script>
<style>
  /*去除upload组件过渡效果*/
  .el-upload-list__item {
    transition: none !important;
  }
</style>
<style scoped lang="scss">


.hide>>>.el-upload--picture-card {
  display: none;
}
</style>
/v1/admin/common/upload 这个路径下的接口:
@PostMapping("/upload")
@ResponseBody
public AjaxResult uploadImg(@RequestParam("file") MultipartFile fileupload){
    if(fileupload != null){
        String path = OssFileUtils.uploadSingleFile(fileupload);//上传图片
        return AjaxResult.success(path);
    }else {
        return AjaxResult.error();
    }
}




/**
 * @ClassName: DesignFileUtils
 * @Description: 文件操作工具类
 * @Author: 
 * @Date: 
 * @Version 1.0
 **/
public class OssFileUtils {
    /**
     * @Title: uploadSingleFile
     * @Description:  单个文件上传
     * @Author:
     * @param: file
     * @Date: 
     * @return: java.lang.String 成功返回 文件路径,失败返回null
     * @throws: 
     */
    public static String uploadSingleFile(MultipartFile file){
        if(file == null){
            log.error("单文件上传失败,文件为空");
            return null;
        }
        try {
            return OssUtil.upload(OssUtil.generateKey(file.getOriginalFilename()),file.getBytes());
        } catch (Exception e) {
            log.error("单文件上传异常【"+file+"】",e);
        }
        return null;
    }
}

找了很久也不知道是哪里导致的,直到把引用这个组件的地方改了,它就好了。之前在引用组件时还写了很多参数,现在只剩下 v-model="dialogForm.imgUrl" 就正常了。

 

  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个使用SpringMVC和Vue.js实现多图片上传的示例代码: 前端页面代码(使用Vue.js): ```html <template> <div> <input type="file" ref="fileInput" @change="handleFileUpload" multiple> <button @click="uploadFiles">上传文件</button> </div> </template> <script> export default { data() { return { files: [] } }, methods: { handleFileUpload() { this.files = this.$refs.fileInput.files; }, uploadFiles() { let formData = new FormData(); for (let i = 0; i < this.files.length; i++) { formData.append("files", this.files[i]); } axios.post("/upload", formData, { headers: { "Content-Type": "multipart/form-data" } }).then(response => { console.log(response.data); }).catch(error => { console.log(error); }); } } } </script> ``` 后端代码(使用SpringMVC): ```java @PostMapping("/upload") @ResponseBody public List<String> upload(@RequestParam("files") MultipartFile[] files) throws IOException { List<String> fileNames = new ArrayList<>(); for (MultipartFile file : files) { if (!file.isEmpty()) { String fileName = file.getOriginalFilename(); String uuid = UUID.randomUUID().toString(); String saveFileName = uuid + "_" + fileName; file.transferTo(new File("/path/to/save/" + saveFileName)); fileNames.add(saveFileName); } } return fileNames; } ``` 这个示例代码使用了Vue.js来实现前端页面的交互,使用了axios库来发送文件上传请求。后端使用了SpringMVC的MultipartFile来处理文件上传请求。在处理每个文件时,可以根据需要对文件进行一些额外的处理,例如:获取文件大小、文件类型等。 希望这个示例代码可以帮助到您!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值