【学习记录21】Vue+ElementUI el-upload多文件上传,一次请求上传多个文件!

前情回顾说点废话。。。

1、项目当中遇到需要上传多个图片,一次选取多个图片。但是吧el-upload默认只能一个一个传,每次上传成功还的自己去push,一个一个去判断。

2、关键是后台给的接口,要一次性接收一堆,无奈之下只能去网上搜索,大佬们都是给的代码片段无法直接使用。

3、经过各种搬运后实现了效果,闲下来就想着自己写一下我最后在代码中实现方法吧。大家共同学习进步,我也巩固一下知识点!有问题的地方欢迎各位大佬指正!

话不多说直接撸代码!!!

html部分

//  :auto-upload="false"    这一句必须加上,阻止默认上传事件     
//  :http-request="BSuploadFile"   上传到服务器的方法
//  :before-upload="beforeUpload" 上传到服务器前校验文件,选择文件的时候不校验,点击“上传到服务器”调用upload()方法的时候执行
//  :on-preview="handlePictureCardPreview"  预览图片
//  :on-remove="BShandleRemove"  删除图片
//  :on-change="changeFileLength"  选择文件后执行
//  multiple
//  :file-list="BSfileList"
<el-upload
              list-type="picture-card"
              class="upload-demo"
              action=""
              ref="upload"
              :auto-upload="false"
              :http-request="BSuploadFile"
              :before-upload="beforeUpload"
              :on-preview="handlePictureCardPreview"
              :on-remove="BShandleRemove"
              :on-change="changeFileLength"
              multiple
              :file-list="BSfileList">
              <i class="el-icon-plus"></i>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件,且不超过1Mb
                <el-button @click="upload" type="success">上传到服务器</el-button>
              </div>
</el-upload>

 喏,没选择文件的时候就是下面的样子

 

 选完文件以后是下面的样子

扫描二维码关注公众号,回复: 16446418 查看本文章

js部分

// 上传到服务器前的校验
beforeUpload(file) {
        console.log('上传前:',file)
// 打印出来看一下格式,file流有时候在file.raw中
        if (file&&file.type) {
          const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png' || file.raw.type === 'image/jpeg' || file.raw.type === 'image/png');
          const isLt1M = file.size / 1024 / 1024 < 1;

          if (!isJPG) {
            this.$message.error('上传头像图片只能是 JPG、PNG 格式!');
          }
          if (!isLt1M) {
            this.$message.error('上传头像图片大小不能超过 1MB!');
          }
          return isJPG && isLt1M;
        } else {
          this.$message.error('文件格式错误,请检查!');
          return false
        }

},
// 选择文件,修改当前文件列表长度后
changeFileLength(singleFile, fileList){
        console.log('修改当前文件', singleFile, fileList)
        this.filesLength = fileList.length
        this.BSfileList = fileList
},
// 用户点击上传调用
async upload(){
        console.log('点击上传')
        // 触发上传 调用配置 :http-request="BSuploadFile"
        // 即触发 uploadFile函数
        await this.$refs.upload.submit();
        // 上传完成后执行的操作 ...
},
// 自定义上传文件,也就是上传到服务器的方法
BSuploadFile(param) {
        console.log('开始上传')
       

        // 当BSfileList长度等于用户需要上传的文件数时进行上传
        if (this.BSfileList.length == this.filesLength){
          // 创建FormData上传
          let fd = new FormData()
          // 将全部文件添加至FormData中
          this.BSfileList.forEach(file => {
            // 第一个参数可改,看后台接口接收什么就改成什么。
            // 第二个参数,是没一个文件的文件流,有时候是file,有时候是file.raw
            // 打印出来,根据时间情况来传入。我也不知道为什么,可能是elm版本封装的json格式不一样
            fd.append('file', file.raw)  
          })
          // 配置请求头,基本上所有上传文件用的都是form-data类型
          const config = {
            headers: {
              "Content-Type": "multipart/form-data",
            }
          }
          // 上传文件,看自己怎么用,没封装过ajx就用全局axios
          // this.axost.post("/abc/upload", fd, config).then(res => {
          multipleTbrandCultureFile(fd, config).then(res => {
            /*上传成功处理*/
            console.log(res)
            this.form.abcFiles = res.data
          }).catch(err => {/*报错处理*/});
        }
}

改进

实践出真理,在使用中发现的问题,上面的写法,校验只会出现弹窗,功能不对,优化后的代码如下。



// 自定义上传文件,也就是上传到服务器的方法
BSuploadFile(param) {
    console.log('开始上传')

    // 在此处加上校验
    // 删除html中的:before-upload="beforeUpload"
    const isgo = this.beforeUpload(file.file)
    if (isgo) {

        // 当BSfileList长度等于用户需要上传的文件数时进行上传
        if (this.BSfileList.length == this.filesLength){
          // 创建FormData上传
          let fd = new FormData()
          // 将全部文件添加至FormData中
          this.BSfileList.forEach(file => {
            // 第一个参数可改,看后台接口接收什么就改成什么。
            // 第二个参数,是没一个文件的文件流,有时候是file,有时候是file.raw
            // 打印出来,根据时间情况来传入。我也不知道为什么,可能是elm版本封装的json格式不一样
            fd.append('file', file.raw)  
          })
          // 配置请求头,基本上所有上传文件用的都是form-data类型
          const config = {
            headers: {
              "Content-Type": "multipart/form-data",
            }
          }
          // 上传文件,看自己怎么用,没封装过ajx就用全局axios
          // this.axost.post("/abc/upload", fd, config).then(res => {
          multipleTbrandCultureFile(fd, config).then(res => {
            /*上传成功处理*/
            console.log(res)
            this.form.abcFiles = res.data
          }).catch(err => {/*报错处理*/});
        }

    }
}


猜你喜欢

转载自blog.csdn.net/wenhui6/article/details/129850762