vue合家福实例(6):文件上传组件自定义ajax请求

element-ui提供了文件上传的组件,官方文档。官方文档还是比较详细的。这里是一点实际应用。这里用了头像上传和照片墙

官方示例

效果






第一个问题:上传图片的时候跨域错误。这个问题就不在这里解决了,实际项目中不会用这个地址上传。
第二个问题:换成自己的服务器地址,vue项目中我用的是axios进行ajax请求。所有的ajax都在/src/request中统一管理。还有服务器的接口是要带access_token才允许访问上传图片的接口的。
假如我的上传请求如下:

// IMAGE api
import Service from '../base'
export default {
  uploadImage (file, handleProgress) {
    const formData = new FormData()
    formData.append('file', file)
    return Service.post('/zuul/image/upload', formData, {
      progress (e) {
        if (e.total > 0) {
          e.percent = e.loaded / e.total * 100
        }
        if (handleProgress) {
          handleProgress(e)
        }
      },
      onUploadProgress (e) {
        if (e.total > 0) {
          e.percent = e.loaded / e.total * 100
        }
        if (handleProgress) {
          handleProgress(e)
        }
      }
    })
  }
}

access_token在base中统一处理。这样就要修改组件的参数了。

  1. action的值改成'upload',不使用组件的这个参数上传文件;
  2. 增加参数:http-request="handleUploadImage"。用自己的方法进行上传。这个回调函数中实现上传业务;
  3. 实现handleUploadImage函数
    handleUploadImage (options) {
      return new Promise((resolve, reject) => {
        FileService.uploadImage(options.file, options.onProgress).then(res => {
          resolve(res)
        }).catch(error => {
          this.$message.error(error || '上传图片失败!')
        })
      })
    }

经过这样修改,上传的过程可以在FileService.uploadImage中控制,上传后结果返回到on-success回调的第一个参数中。进度会传回FileService.uploadImage第二个参数指向的函数中。
最终代码







你可能感兴趣的:(vue合家福实例(6):文件上传组件自定义ajax请求)