1、图片上传

图片上传和文件上传的上传原理相同

  • 主要思路:上传相关数据使用imageList,组件绑定数据使用fileList。数据加载时imageList和fileList同时赋值,数据提交时使用imageList。
    (不能都使用fileList,上传时会出现2个文件-----上传成功的回传。)
---------------------html---------------------
<van-field
        label-align="left"
        name="uploader"
        required
        label="附件"
       >
    <template #input>
    <van-uploader v-model="fileList"
                   type="primary"
                  :max-count="1"
                 :after-read="uploadImage"
               :before-delete ="deleteImage"
    />
/>
------------------------js-----------------------
// 图片上传
uploadImage (file) {
  file.status = 'uploading';
  file.message = '上传中...';
  this.uploadImg(file,file.file)
},
uploadImg (uploadFile,file) {
  let formdata = new FormData();
  formdata.append('file', file, file.name);
  // 设置请求头
  let config = {
    headers:{
      'Content-Type':'multipart/form-data'
    }
  };
  const axiosAjax = axios.create({
    timeout: 1000 * 60, // 时间
    withCredentials: true // 跨域携带cookie
  });
  const url = window.SITE_CONFIG['baseUrl'] + this.uploadURL
  axiosAjax.post(url, formdata, config).then((res) => {
    uploadFile.status = 'done'
    uploadFile.message = '上传成功'
    this.imageList.push({'name': res.data.data.name, 'url': res.data.data.url,'uid': res.data.data.fileId,'status': 'success'})
  }).catch(() => {

  })
},
// 附件删除
deleteImage (url, img) {
  this.imageList.filter((item, indexs) => {
    if (img.index === indexs) {
      this.imageList.splice(indexs, 1)
    }
  })
  return true
},

2、服务器图片回显

上传时组件自身会处理回显,不需要单独处理。此处的回显是指从api返回的图片资源的加载。需要对fileList数据进行处理才能显示图片。van-uploader组件显示服务器资源时需要特定的格式。因此对图片返回值对象files进行处理来实现。

// 加载图片数据处理
JSON.parse(files).forEach((item, index) => {
  letf ss = {
    id: item.uid,
    name: item.name,
    isImage: true,
    url: this.con + item.url,
    file: new File([], item.name, {})
   }
   this.fileList.push(ss)
   this.imageList.push(item)
 }),
Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐