vue使用axios上传文件

1.安装axios

cnpm i axios -S

2.方案一:修改原型链

首先,在main.js中引入

在这个时候,你还是无法在组件中使用axios的,但如果将vue改为vue的原型链,就可以解决这个问题,如下图

开始发送请求

//获取表单中的file	
var file_obj = document.getElementById('fileaaa').files[0];
		alert(file_obj)
		console.log(file_obj);
		let formdata = new FormData()
		formdata.append('file', file_obj)
		formdata.append('title', "sadasdsa")
		formdata.append('url', "urlsadsasaassad")

		this.$ajax.post('/index/addBanner', formdata, {
		    headers: {
			    "Content-Type": "multipart/form-data"
				         }
					})
					.then(function(response) {
						console.log(response);
					})

			},

成功

axios封装:

//封装全局axios,可以做请求拦截和响应拦截
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { ElLoading } from 'element-plus';

// 创建一个 axios 实例
const service = axios.create({
  baseURL: '/api', // 所有的请求地址前缀加的部分
  timeout: 6000, // 请求超时时间毫秒
  withCredentials: true, // 异步请求携带cookie
  headers: {
    // 设置后端需要的传参类型
    'Content-Type': 'application/json',
    'token': 'your token',
    'X-Requested-With': 'XMLHttpRequest',
  },
})

//全局的遮罩层动画效果
let loading: any;
const startLoading = () => {
  interface Options {
    lock: boolean;
    text: string;
    background: string;
  };

  const options: Options = {
    lock: true,
    text: "加载中...",
    background: 'rgba(0,0,0,0.7)'
  }
  loading = ElLoading.service(options);
}

const endLoading = () => {
  loading.close();
}

// 请求拦截时候加载一个全局的遮罩层动画效果
service.interceptors.request.use((config: AxiosRequestConfig<any>) => {
  // 加载全局的遮罩层动画效果
  startLoading()
  console.log("测试请求-------loading全局的遮罩层动画效果")
  return config;
})

// 响应拦截
service.interceptors.response.use((response: AxiosResponse<any>) => {
  // 结束loading全局的遮罩层动画效果
  endLoading();
  console.log("测试loading全局的遮罩层动画效果")
  return response;
}, error => {
  // 结束loading全局的遮罩层动画效果
  endLoading();
  // 对响应错误做点什么
  console.log("error-response:", error.response);
  console.log("error-config:", error.config);
  console.log("error-request:", error.request);
  if (error.response) {
    console.log("服务器请求异常");
  }
  // 错误提醒
  return Promise.reject(error);
})

export default service;

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值