vant中uploader上传图片

1.html部分

<van-field name="uploader" label="上传图片">
   <van-uploader  :before-read="beforeRead" :after-read="afterRead" :delete="deleteImg" slot="input" v-model="imageList" multiple :max-count="4" />
</van-field>

//其中:
//before-read:文件读取前的回调函数,返回 false 可终止文件读取,支持返回 Promise
//after-read:文件读取完成后的回调函数
//delete:删除文件预览时触发,同after-read
//multiple:是否开启图片多选,部分安卓机型不支持
//max-count:文件上传数量限制

2.js部分

data () {
    return {
        uploadImage: [],
    }
}


beforeRead (file) {
      if (file instanceof Array && file.length) {
        file.forEach(item => {
          if (item.type !== 'image/jpeg' && item.type !== 'image/png' && item.type !== 'image/jpg') {
            this.$toast.fail('请选择正确图片格式上传')
            return false
          }
        })
        return file
      } else {
        if (file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/jpg') {
          this.$toast.fail('请选择正确图片格式上传')
          return false
        }
        return file
      }
},

afterRead (file) {
      if (file instanceof Array && file.length) {
        file.forEach(item => {
          this.uploadImage.push(item.file)
        })
      } else {
        this.uploadImage.push(file.file)
      }
 },
//删除方法
deleteImg (file) {
      for (let i = 0, len = this.uploadImage.length; i < len; i++) {
        if (file.file.name === this.uploadImage[i].name && file.file.size === this.uploadImage[i].size) {
          this.uploadImage.splice(i, 1)
          break
        }
      }
}, 
//或        
// deleteImage (file) {
//   const index = this.uploadImage.indexOf(file.file)
//   this.uploadImage.splice(index, 1)
// },

3、上传至服务器

上传过程中可以给button添加loading效果避免用户重复点击

单张返回对象,多个返回数组
instanceof用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上
用于区分单张还是多张
单张--直接append添加
多张--循环回调数组,依次把每个图片添加进去

async uploadFile () {
    if (this.uploadImage && this.uploadImage.length) {
      this.btnLoading = true
      const params = new FormData()
      this.uploadImage.forEach(item => {
         params.append('files', item)
       })
       const data = await uploadFile(params)
       this.btnLoading = false
        this.imageUrl = data.returnPath
        if (data.returnPath) {
          this.uploadImage = []
          this.patrolReport()
        }
      } else {
        this.patrolReport()
     }
},

4、遇到的问题

4.1、图片上传413
可能为该问题

nginx 出现413 Request Entity Too Large问题的解决方法

使用tomcat/manager(大小4.1M),出现 nginx: 413 Request Entity Too Large 错误。 
根据经验是服务器限制了上传文件的大小

原来nginx默认上传文件的大小是1M,可nginx的设置中修改。

解决方法如下: 
1.打开nginx配置文件 nginx.conf, 路径一般是:/etc/nginx/nginx.conf。 
2.在http{}段中加入 client_max_body_size 20m; 20m为允许最大上传的大小。 
3.保存后重启nginx,问题解决:service nginx restart
例:
server {
    listen       80;
    server_name  localhost;
	client_max_body_size 10M;
    //client_max_body_size 10M 要放在server下的server_name下,放在localhost /web的大括号里有时不生效
	location /web {
        alias   D:/web;
        index main.html;			
   }
	location /web/service {
       proxy_pass   http://192.168.1.188:8080/service;		
   }
	location /web/service/upload {
       proxy_pass   http://192.168.1.188/upload;
   }		
}
4.2、服务器修改限制之后上传图片也不成功,也不失败。无提示
根据后台查看超时。

由于前端在封装axios的时候在请求头中设置了超时时间,导致多图片的时候图片还未上传完就已经超时,接口没有返回,这个时候可以将超时时间适当延长。
4.3、其他问题(下载excel文件)
export function exportInfoList(params) {
    return HttpRequestDownload({
        method: 'post',
        loading: true,
        responseType: 'blob',
        url: 'exportFile',
        data: params
    })
}

exportListFun() {
  exportInfoList(this.exportQueryInfo).then((data) => {
    var elink = document.createElement("a");
    elink.download = `detector.xlsx`;
	elink.style.display = "none";
	var blob = data.request.response;
	elink.href = URL.createObjectURL(blob);
	document.body.appendChild(elink);
	elink.click();
	document.body.removeChild(elink);
  });
}

	注意:一般接口返回的文件流在data中,但是有时候不是,问清楚后端返回的文件流放在data目录下的什么地方。不然就是后端说他返回了,但是前段没有找到文件流。
    

类似: // bolb类文件对象 Blob(4412) {size: 4412, type: "application/octet-stream"}
 
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐