原生js上傳圖片遇到的坑(axios封裝)

後臺給我寫了一個上傳圖片的接口,本身用form表單測試成功css

 

 

 接口能夠正常跳轉html

 

 

 測試的代碼:jquery

<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="Generator" content="EditPlus®">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <title>Document</title>
 </head>
 <body>
  <form method="POST" action="http://192.168.79.191:8889/api/upload/uploadFile" enctype="multipart/form-data">
    <table>
        <tr>
            <td><label path="file">Select a file to upload</label></td>
            <td><input type="file" name="file" id="upload_file"/></td>
        </tr>
        <tr>
            <td>fileGroup: <input name = "fileGroup" type = "text"><br></td>
        </tr>
        <tr>
            <td>flag:<input name = "flag" type = "text"><br></td>
        </tr>
        <tr>
            <td><input type="submit" value="Submit"/></td>
        </tr>
    </table>
</form>
 </body>
</html>
View Code

 

由於這樣用form表單提交的時候會自動跳轉,因此就想到用js模擬form表單提交ios

 

代碼一寫完,問題來了,用axios請求不成功,web

let file = e.target.files[0]
var formData = new FormData()
formData.append('file', file)
this.$ajax.post(Api.uploadFile, formData).then(function(response) {
    alert(123)
    //this.$refs.loading.show()
    if (response.data.status === -1) {
        //this.promptText = response.data.msg
        //this.$refs.prompt.show()
    } else {
        //this.front_pic = this.publicUrl + response.data.data.url // 提交圖片獲取URL,返回
    }
}, function() {
    this.promptText = '請求失敗'
    this.$refs.prompt.show()
})

 

 

而後我想axios不成功,那我換成了原生的ajax請求應該行了吧結果仍是不成功,代碼以下ajax

/*原生請求方式 */
let xhr = new XMLHttpRequest();  // XMLHttpRequest 對象
xhr.open("post", "http://localhost:8082/api/files/api/upload/uploadFile", true); //post方式,url爲服務器請求地址,true 該參數規定請求是否異步處理。
xhr.setRequestHeader('content-type', 'multipart/form-data')//不要自做多情加上這一句 //xhr.setRequestHeader('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8')
xhr.send(formData); //開始上傳,發送form數據
xhr.onreadystatechange = function () {
    var data = xhr.responseText;
    console.log(data);
}

控制檯 network  就是請求不成功,500報錯json

 

 錯誤信息以下axios

 

 

整了大半天,最後發現是不用設置content-type   一去掉就正常了  真的是自做多情 本身設置了content-type致使請求不成功api

總結問題:服務器

第一:axios不成功

緣由:

一、自做多情設置了content-type(攔截器李阿敏)

//http request 攔截器
axios.interceptors.request.use(
  config => {
    config.headers = {
      //'Content-Type':'application/x-www-form-urlencoded'
      'Content-Type': 'multipart/form-data'
    }
    return config;
  },
  error => {
    return Promise.reject(err);
  }
);

 

二、axios可能將請求污染

解決辦法:

請求以前先new 一個全新的axios  以下

    uploadImage(e){
      let instance = axios.create();//請求以前先new一個全新的axios
      let file = e.target.files[0]
      const formDate = new FormData()
      formDate.append('file', file)

      instance.post('/files/api/upload/uploadFile',formDate).then((res)=>{
            console.log(res);
            if(res.status && res.status == 500){
                this.error='用戶名或密碼錯誤!'
            }else if(res.access_token){
                let millisecond = new Date(new Date().getTime() + res.expires_in * 1000);   //access_token過時時間
                cookies.set('access_token',res.access_token,{expires: millisecond});    //設置cookie
                this.$router.replace("/");  //登陸到首頁
            }
        })
    }

上面代碼:正常,能夠請求成功,問題獲得解決

 

第二:原生的ajax不成功

緣由  設置了content-type

解決辦法:將content-type去掉

 

 

 

上傳圖片組件代碼

<template>
    <div class="param-pannel">

        <common-prm/>
        <border-prm myStyle="style" />
        <collapse-item title="圖片">

            <div class="param-gap">
                <label class="left" for="">路徑&nbsp;:</label>
                <div class="right">

                    <input type="file" 
                    name="file"
                    ref="input"
                    enctype="multipart/form-data"
                    accept="image/gif,image/jpeg,image/jpg,image/png,image/svg" 
                    multiple="multiple" 
                    @change="getFile" 
                    class="data-value" />

                </div>
            </div>

        </collapse-item>
    </div>
</template>
<script>
import axios from 'axios'
import mixins from '../paramMixins.js'
import Api from '@frameworks/conf/api'
export default {
    name: 'ImgParam',
    mixins: [mixins],
    data() {
        return {
            textName: '文本'
        }
    },
    methods: {
        getFile(e) {
            //驗證
            if (e.target.files[0].size >= 1048576) {
                alert("上傳圖片大小不得超過1M");
                return false;
            }
            // 預覽圖片
            var reader = new FileReader();
            let _this = this
            reader.onload = (function(file) {
                return function(e) {
                    var datainfo = this.result;
                    _this.params.images = datainfo
                    _this.updateData()
                    
                };
            })(e.target.files[0]);
            reader.readAsDataURL(e.target.files[0]);
            //上傳
            this.upload(e.target.files[0])
        },
        //調用上傳圖片的接口上傳
        upload(file){
            var formData = new FormData()
            formData.append('file', file)
            /*axios請求方式 */
            this.$ajax.upload(Api.uploadFile, formData).then(function(response) {
                if (response.data.status === -1) {
                    alert()
                } else {

                }
            }, function() {
                this.promptText = '請求失敗'
                this.$refs.prompt.show()
            })
            //axios封裝的post請求(不成功)
            /*this.$ajax.post(Api.uploadFile, formData).then(function(response) {
                alert(123)
                
            }, function() {
                this.promptText = '請求失敗'
                this.$refs.prompt.show()
            })*/
            /*原生請求方式(成功) */
            // let xhr = new XMLHttpRequest();  // XMLHttpRequest 對象
            // xhr.open("post", "http://localhost:8082/api/files/api/upload/uploadFile", true); //post方式,url爲服務器請求地址,true 該參數規定請求是否異步處理。
            // //xhr.setRequestHeader('content-type', 'multipart/form-data')
            // //xhr.setRequestHeader('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8')
            // xhr.send(formData); //開始上傳,發送form數據
            // xhr.onreadystatechange = function () {
            //     var data = xhr.responseText;
            //     console.log(data);
            // }
        }
    }
}
</script>

<style scoped lang="scss">
.param-pannel input,
.param-pannel select {
    border: 1px solid #ddd;
    width: 100%
}

.param-pannel>div {
    padding: 5px 0;
}
</style>


<style scoped lang="scss">
@import '../../../assets/css/params_common.scss';
</style>
View Code

 

封裝的axios

import axios from 'axios';
import {axios_defaults_timeout} from '@frameworks/conf/config'
import qs from 'qs'

axios.defaults.timeout = axios_defaults_timeout;
axios.defaults.baseURL = JSON.parse(process.env.VUE_APP_MICRO_SERVICE)?process.env.VUE_APP_URL:process.env.VUE_APP_SINGLEURL; //填寫域名

//http request 攔截器
axios.interceptors.request.use(
  config => {
    config.headers = {
      //'Content-Type':'application/x-www-form-urlencoded'
      'Content-Type': 'multipart/form-data'
    }
    return config;
  },
  error => {
    return Promise.reject(err);
  }
);

//響應攔截器即異常處理
axios.interceptors.response.use(response => {
    return response
}, err => {
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          return Promise.resolve({status:err.response.status,message:'錯誤請求'});
          break;
        case 401:
          return Promise.resolve({status:err.response.status,message:'未受權,請從新登陸'});
          break;
        case 403:
          return Promise.resolve({status:err.response.status,message:'拒絕訪問'});
          break;
        case 404:
          return Promise.resolve({status:err.response.status,message:'請求錯誤,未找到該資源'});
          break;
        case 405:
          return Promise.resolve({status:err.response.status,message:'請求方法未容許'});
          break;
        case 408:
          return Promise.resolve({status:err.response.status,message:'請求超時'});
          break;
        case 500:
          return Promise.resolve({status:err.response.status,message:'服務器端出錯'});
          break;
        case 501:
          return Promise.resolve({status:err.response.status,message:'網絡未實現'});
          break;
        case 502:
          return Promise.resolve({status:err.response.status,message:'網絡錯誤'});
          break;
        case 503:
          return Promise.resolve({status:err.response.status,message:'服務不可用'});
          break;
        case 504:
          return Promise.resolve({status:err.response.status,message:'網絡超時'});
          break;
        case 505:
          return Promise.resolve({status:err.response.status,message:'http版本不支持該請求'});
          break;
        default:
          return Promise.resolve({status:err.response.status,message:'未知錯誤'});
          break;
      }
    } else {
      return Promise.resolve({status:err.response.status,message:'鏈接到服務器失敗'});
    }
    return Promise.resolve(err.response)
})


/**
 * 封裝get方法
 * @param url
 * @param data
 * @returns {Promise}
 */
export function fetch(url,params={}){
  return new Promise((resolve,reject) => {
    axios.get(url,{
      params:params
    })
    .then(response => {
      if(response.data) resolve(response.data);
    })
    .catch(err => {
      reject(err)
    })
  })
}


/**
 * 封裝上傳圖片upload的方法
 * @param url
 * @param data
 * @returns {Promise}
 */
 export function upload(url,data = {}){
   let instance = axios.create();
   return new Promise((resolve,reject) => {
     instance.post(url,data)
      .then(response => {
        if(response.data) resolve(response.data);
      },err => {
        reject(err)
      })
   })
 }

/**
 * 封裝post請求
 * @param url
 * @param data
 * @returns {Promise}
 */
 export function post(url,data = {}){
   return new Promise((resolve,reject) => {
     axios.post(url,qs.stringify(data))
      .then(response => {
        if(response.data) resolve(response.data);
      },err => {
        reject(err)
      })
   })
 }

 /**
 * 封裝patch請求
 * @param url
 * @param data
 * @returns {Promise}
 */
export function patch(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.patch(url,data)
         .then(response => {
           if(response.data) resolve(response.data);
         },err => {
           reject(err)
         })
  })
}

 /**
 * 封裝put請求
 * @param url
 * @param data
 * @returns {Promise}
 */
export function put(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.put(url,data)
         .then(response => {
           if(response.data) resolve(response.data);
         },err => {
           reject(err)
         })
  })
}

 /**
 * 封裝delete請求
 * @param url
 * @param data
 * @returns {Promise}
 */
export function del(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.delete(url,data)
         .then(response => {
           if(response.data) resolve(response.data);
         },err => {
           reject(err)
         })
  })
}


 /**
 * 封裝異步Ajax請求
 * @param url
 * @param data
 * @returns {Promise}
 */
export async function syncAjax (url = '',method = 'get',data = {},callbackr = ()=>{},callbackw = ()=>{}) {
  try {
    let response = await axios({ method, url, data })
    callbackr && callbackr(response)
    return Promise.resolve(response)
  } catch (err) {
    callbackw && callbackw(err)
    return Promise.reject(err)
  }
}

const ajax = {
  fetch,post,patch,put,del,syncAjax,upload
}

export default ajax
View Code

 

封裝的jq ajax

import $ from 'jquery';

export default function jqueryAjax(url,method,async,data,callbackr,callbackw) {
  $.ajax({
    url: url, //url路徑
    type: method, //GET
    async: async, //或false,是否異步
    data: data,
    timeout: 5000, //超時時間
    dataType: 'json', //返回的數據格式
    beforeSend: function(xhr) {},
    success: function(data, textStatus, jqXHR) {
      callbackr && callbackr(data);
    },
    error: function(xhr, textStatus) {
      callbackw && callbackw(xhr);
    },
    complete: function() {}
  })
}
View Code

 

 

相關文章
相關標籤/搜索