[axios] Vue文件流上传文件


npm地址

初始化API

import axios from 'axios'
import qs from 'qs'

const http = axios.create({
    // baseURL: 'http://api-test.matixiang.com',
    timeout: 1000,
    headers: {  
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    transformRequest: [function (data) {
        return qs.stringify(data)
    }
    ],
    paramsSerializer: function (data) {
        return qs.stringify(data)
    }
})
export default http

#在main.js引入api.js
window.$http = Vue.prototype.$http = http

文件流上传图片

# html
<form id="formid">
    <label for="resource">上传文档</label>
    <input type="file" id="resource" name="resource" ref="resource">
    <button type="button" @click="upload()">上传</button>
</form>

JavaScript

var formData = new FormData() // FormData 对象
formData.append('file', this.$refs.resource.files[0])
this.$http.post('http://192.168.1.200:3001/api/upload/sina', formData, {
    method: 'post',
    headers: {
        'Content-Type': 'multipart/form-data'
    },
    transformRequest: [function (data) {
        return data
    }],
    onUploadProgress: function(e) {
        let percentage = Math.round((e.loaded * 100) / e.total) || 0
        console.log(e, percentage)
    }
}).then((response) => {
    if (response.data.status) {} else {
        this.$Notice.error({
            title: '错误',
            message: response.data.imgId
        })
    }
}).catch(function (error) {
    console.log(error)
})

参考:

声明:Shire | 一路走一路记|版权所有,违者必究|如未注明,均为原创|本网站采用BY-NC-SA协议进行授权

转载:转载请注明原文链接 - [axios] Vue文件流上传文件


Carpe Diem and Do what I like