前后端分离的情况下进行图片上传

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32768743/article/details/85164632

这个需求本质上和没有分离的时候没啥区别,在Vue前端的写法,可以参考:Vue+SpringBoot实现前后端分离的文件上传
我在写的时候
封装axios, iview-admin的写法

import axios from 'axios'
class HttpRequest {
  constructor (baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {
      }
    }
    return config
  }
  destroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // Spin.show() // 不建议开启,因为界面不友好
      }
      this.queue[url] = true
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url)
    }, error => {
      this.destroy(url)
      return Promise.reject(error)
    })
  }
  request (options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    console.debug(options.url)
    return instance(options)
  }
}
export default HttpRequest

自己的请求

export default {
  upload: (file, usage) => {
    const data = new FormData()
    data.append('file', file)
    return axios.request({
      url: 'file',
      data,
      method: 'post'
    })
  },
}

然后配合iview的upload组件就行了
划重点

const data = new FormData()
    data.append('file', file)

猜你喜欢

转载自blog.csdn.net/qq_32768743/article/details/85164632