当前位置: 首页 > 工具软件 > getbase > 使用案例 >

antd vue 上传图片 - Base64格式、文件流格式

乌璞瑜
2023-12-01
1、为什么上传图片需要使用base64格式进行转换,再传给后端?当上传的图片很小的时候,转成base64格式较为划算。

贴代码:
HTML:

 <a-form-item
    label="图片上传"
    :label-col="labelCol"
    :wrapper-col="wrapperCol">
    <a-upload
      :custom-request="customRequest"
      name="file"
      :headers="{'Authorization':token}"
      list-type="picture-card"
      v-decorator="[
        'upload',
        {
          initialValue:fileList,
          valuePropName: 'fileList',
          getValueFromEvent: normFile,
          rules: [{ required: false, message: '请选择图片' }]
        },
      ]"
      @change="handleChange"
      @preview="handlePreview">
      <div v-if="fileList.length < maxLength">
        <a-icon type="plus" />
        <div class="ant-upload-text">
          Upload
        </div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </a-form-item>

JS部分:

	// files上传
    handleChange ({ file, fileList }) {
      this.fileList = fileList
      if (status === 'error') {
        this.$message.error(`上传失败`)
      }
    },
    // 自定义上传图片
	 async customRequest (obj) {
      const response = {
        uid: obj.file.uid,
        name: obj.file.name,
        status: 'done',
        url: ''
      }
      // onProgress进度条
      obj.onProgress({ percent: 50 })
      const param = await this.getBase64(obj.file)
      // 图片接口
      getUploadImg({ tpnr: param, type: 2 }).then((res) => {
        obj.onProgress({ percent: 100 })
        response.url = res.data
        obj.onSuccess(response, obj.file)
      }).catch((err) => {
        obj.onError(err)
        console.log(1234)
      })
    },
    // 将上传的文件转成base64格式
    getBase64 (file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => resolve(reader.result)
        reader.onerror = error => reject(error)
      })
    },
    // 图片预览
    async handlePreview (file) {
      if (!file.url && !file.preview) {
        file.preview = await this.getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    // 关闭预览图片遮罩层
    handleCancel () {
      this.previewVisible = false
    },
    // 可以把 onChange 的参数转化为控件的值
    normFile (e) {
      if (Array.isArray(e)) {
        return e
      }
      return e && e.fileList
    }
2、使用文件流的方式上传图片

html:

	<a-form-item
            :prop="required?'imgData':null"
            label="图片上传"
            :label-col="labelCol"
            :wrapper-col="wrapperCol">
            <a-upload
              :action="`${baseURL}/upload`"
              name="file"
              :headers="{'Authorization':token}"
              list-type="picture-card"
              v-decorator="[
                'upload',
                { initialValue:fileList,
                  valuePropName: 'fileList',
                  getValueFromEvent: normFile,
                  rules: [{ required: required, message: '请选择图片' }]
                },
              ]"
              @change="handleChange"
              @preview="handlePreview">
              <div v-if="fileList.length < maxLength">
                <a-icon type="plus" />
                <div class="ant-upload-text">
                  Upload
                </div>
              </div>
            </a-upload>
            <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
              <img alt="example" style="width: 100%" :src="previewImage" />
            </a-modal>
          </a-form-item>

JS代码:

	// files上传
    handleChange ({ fileList }) {
     this.fileList = fileList
    },
    // 图片预览
	async handlePreview (file) {
      if (!file.url && !file.preview) {
        file.preview = await this.getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    // 关闭预览
     handleCancel () {
      this.previewVisible = false
    },
     normFile (e) {
      if (Array.isArray(e)) {
        return e
      }
      return e && e.fileList
    },
    // 提交表单
    handleSubmit () {
      return new Promise((resolve, reject) => {
        this.form.validateFields(async (err, values) => {
          if (!err) {
            const fileImgList = []
           this.fileList.map((item, index) => {
              // 处理提交的图片list
              fileImgList.push(item.response.data.picUrls[0])
            })
            resolve(fileImgList)
          } else {
            reject(err)
          }
        })
      })
    }
 类似资料: