本文實(shí)例為大家分享了Vue formData實(shí)現(xiàn)圖片上傳的具體代碼,供大家參考,具體內(nèi)容如下
import Vue from 'vue' /** * 圖片上傳 * 已注入所有Vue實(shí)例, * template模板里調(diào)用 $uploadFile(id) * 組件方法里調(diào)用 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') // 數(shù)據(jù)請(qǐng)求 Vue.axiosfrom(Vue.api.upload, formData).then(res => { // 返回圖片url resolve(res) }).catch(err => { reject(err) }) } }) }) return promise} Vue.prototype.$uploadFile = uploadFileaxios請(qǐng)求頭設(shè)置
import Vue from 'vue'import { baseURL } from '@/config/env'import axios from 'axios' // formdata 請(qǐng)求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'}) => { // 帶請(qǐng)求進(jìn)度條成功方法 const sucFunX = res => { return res.data } // 成功執(zhí)行方法 const sucFunC = res => { return res.data } // 帶請(qǐng)求進(jìn)度條失敗方法 const errFunX = err => { console.log(err, NProgress.done()) } // 失敗執(zhí)行訪求 const errFunC = err => { console.log(err) } // 判斷是否需要Longing const sucFun = loading ? sucFunX : sucFunC // 判斷是否需要Longing const errFun = loading ? errFunX : errFunC return {user, sucFun, errFun}} // 表單請(qǐng)求 圖片上傳const axiosfrom = function (url = '', data = {}) { let {sucFun, errFun} = XHR({loading: false}) return axiosT.post(url, data).then(sucFun).catch(errFun)}// 表單請(qǐng)求Vue.prototype.$axiosfrom = axiosfromVue.axiosfrom = axiosfrom以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。
新聞熱點(diǎn)
疑難解答