Vue的formData圖片上傳
阿新 • • 發佈:2018-12-15
import Vue from 'vue' /** * 圖片上傳 * 已注入所有Vue例項, * template模板裡呼叫 $uploadFile(id) * 元件方法裡呼叫 this.$uploadFile(id) */ const uploadFile = (id) => { let promise = new Promise((resolve, reject) => { let file = null let el = null let i = 0 let formData = new FormData() document.getElementById(id).click() el = document.getElementById(id) el.addEventListener('change', function (e) { i++ if (i !== 1) { return false } else { file = this.files[0] formData.append('file', file) formData.append('fileType', 'IMAGE') // 資料請求 Vue.axiosfrom(Vue.api.upload, formData).then(res => { // 返回圖片url resolve(res) }).catch(err => { reject(err) }) } }) }) return promise } Vue.prototype.$uploadFile = uploadFile
axios請求頭設定
import Vue from 'vue' import { baseURL } from '@/config/env' import axios from 'axios' // formdata 請求 const axiosT = axios.create({ baseURL: baseURL, headers: { 'Content-Type': 'multipart/form-data' } }) const XHR = ({method = 'post', qs = true, loading = false, loginRequire = true, reqComplex = false, reqContentType = 'urlencoded'}) => { // 帶請求進度條成功方法 const sucFunX = res => { return res.data } // 成功執行方法 const sucFunC = res => { return res.data } // 帶請求進度條失敗方法 const errFunX = err => { console.log(err, NProgress.done()) } // 失敗執行訪求 const errFunC = err => { console.log(err) } // 判斷是否需要Longing const sucFun = loading ? sucFunX : sucFunC // 判斷是否需要Longing const errFun = loading ? errFunX : errFunC return {user, sucFun, errFun} } // 表單請求 圖片上傳 const axiosfrom = function (url = '', data = {}) { let {sucFun, errFun} = XHR({loading: false}) return axiosT.post(url, data).then(sucFun).catch(errFun) } // 表單請求 Vue.prototype.$axiosfrom = axiosfrom Vue.axiosfrom = axiosfrom