概述
public/config.js
var prod_config = {};
prod_config.BASE_URL = 'https://www.student.com/user' //开发环境
prod_config.publicPath = '/' // 对应vue.config.js的publicPath
prod_config.routerBase = '' // 对应路由的base
public/index.html
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app">
<script src="<%= BASE_URL %>config.js"></script>
</div>
<!-- built files will be auto injected -->
</body>
main.js
import axios from 'axios'
axios.defaults.baseURL = window.prod_config.BASE_URL
src/utils/upload.js
import axios from 'axios'
import { getToken } from '@/utils/auth'
/**
* 封装上传文件的post方法
* @param url
* @param data
* @returns {Promise}
*/
export function upload(url, data) {
return new Promise((resolve, reject) => {
axios.post(url, data, {
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer ' + getToken(),
}
}).then(response => {
resolve(response)
}).catch(error => {
reject(error)
})
})
}
/**
* 封装文件上传的put方法
* @param url
* @param data
* @returns {Promise}
*/
export function uploadPut(url, data) {
return new Promise((resolve, reject) => {
axios.put(url, data, {
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer ' + getToken(),
}
}).then(response => {
resolve(response)
}).catch(error => {
reject(error)
})
})
}
src/api/upload.js
import { upload } from '@/utils/upload'
// 上传文件
export function uploading(data){
return upload('/selfPrint/file/upload',data)
}
xxx.vue 使用
uploadSectionFile(param) {
const file = param.file
console.log('上传的参数', param)
const formData = new FormData()
this.formData.append('file', file)
// 上传后端
uploading(formData).then((response) => {
if (response.code === 200) {
console.log('上传成功', response)
} else {
console.log('上传失败', response)
}
})
},
最后
以上就是矮小鼠标为你收集整理的vue封装文件上传方法的全部内容,希望文章能够帮你解决vue封装文件上传方法所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复