vue-axios配置token,上传图片

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('已上传该图片');
            }
          })
      },

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

posted @ 2017-07-29 15:19  阿狸很酷  阅读(542)  评论(0编辑  收藏  举报