vue-axios配置token,上传图片

it2022-05-09  34

vue1.0用 vue-resource 目前不维护了

vue2.0用 axios

使用

1.安装axios,

npm install axios

2.在main.js中配置

import axios from 'axios' Vue.prototype.$http = axios;  

3.配置main,js中token,每次请求都会自带token

var token = '你自己定义的token' axios.interceptors.request.use( config => { config.headers['后端接收token的字段'] = token return config }, err => { return Promise.reject(err) })

4.上传图片

4.1 html部分代码

<input class="file" name="file" type="file" accept="image/png,image/gif,image/jpeg" @change="update"/>

4.2 script部分

update(e){ let file = e.target.files[0]; let param = new FormData(); //创建form对象 param.append('后端接收图片的字段',file,file.name) console.log(param.get('file')); //FormData私有类对象,访问不到,可以通过get判断值是否传进去 this.uploading(param,file.name); }, uploading(param,pathName){ this.$http.post('接口地址',param) .then(response=>{ console.log(response.data); let localArr = this.images.map((val,index,arr)=>{ return arr[index].localSrc; }) if(!~localArr.indexOf(pathName)){ this.images.push({'src':this.showUrl+response.data.key,'localSrc':pathName}); }else{ alert('已上传该图片'); } }) },

到这就可以实现图片上传了

转载于:https://www.cnblogs.com/jsusu/p/7256022.html

相关资源:数据结构—成绩单生成器

最新回复(0)