1. 程式人生 > 其它 >element-admin 上傳 跨域 問題 http-request

element-admin 上傳 跨域 問題 http-request

感謝

https://www.jianshu.com/p/55c0bd5b5b3e

解決跨域問題的方法之一,使用上傳元件的自定義上傳方法 http-request

一般我們在用element-ui上傳功能時,有個action屬性填寫上傳圖片地址,然後就能運用提供的各種鉤子函式處理成功,失敗等情況,但有時上傳圖片發請求時可能要做些特殊處理,比如跨域、特殊引數等,這是就要用到http-request這個方法了 1.首先要用任意字元覆蓋action屬性
 <el-upload
      class="image-upload-pic"
      ref="upload"
      action
="fakeaction" :show-file-list="false" :http-request="uploadSectionFile" > <img v-if="imageUrl" :src="imageUrl" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload>

2.用自己方法覆蓋預設上傳行為

3.根據請求返回的code就能處理各種情況,不需要利用預設鉤子函式

methods:{
    uploadSectionFile(params) {
          const file = params.file,
            fileType = file.type,
            isImage = fileType.indexOf("image") != -1,
            isLt2M = file.size / 1024 / 1024 < 2;
          // 這裡常規檢驗,看專案需求而定
          if (!isImage) {
            this.$message.error("只能上傳圖片格式png、jpg、gif!");
            
return; } if (!isLt2M) { this.$message.error("只能上傳圖片大小小於2M"); return; } // 根據後臺需求資料格式 const form = new FormData(); // 檔案物件 form.append("file", file); // 本例子主要要在請求時新增特定屬性,所以要用自己方法覆蓋預設的action form.append("clientType", 'xxx'); // 專案封裝的請求方法,下面做簡單介紹 imageUpload(form) .then(res => { //自行處理各種情況 const code = res && parseInt(res.code, 10); if (code === 200) { // xxx } else { // xxx } }) .catch(() => { // xxx }); } }

利用axios簡單封裝的請求

const imageUpload = param => {
    const url = 'xxxxx'
    // 根據後臺需求的資料格式確定headers
    return axios.post(url, params, { 
        headers: {"content-type": "multipart/form-data"}
    })
}

分析覆蓋方法http-request傳入的預設引數

{
    action:"fakeaction"
    data:undefined
    file:File(879394) {uid: 1558602694174, name: "Chrysanthemum.jpg", lastModified: 1247549551674, lastModifiedDate: Tue Jul 14 2009 13:32:31 GMT+0800 (中國標準時間), webkitRelativePath: "", …}
    filename:"file"
    headers:{__ob__: Observer}
    onError:ƒ onError(err)
    onProgress:ƒ onProgress(e)
    onSuccess:ƒ onSuccess(res)
    withCredentials:false
}

發現有觸發預設鉤子函式onError,onProgress,onSuccess的方法,所以你也根據自己圖片上傳請求的結果自己呼叫這些鉤子方法,從而複用預設的ui

破罐子互摔