vue之XMLHttpRequest上传文件

首先得有一个控件用来选择文件

<input type="file" accept="image/*" @change="fileChanged" ref="file">

也可以隐藏file控件然后用其他事件触发file控件的chagne事件

this.files = this.$refs.file.files     //将控件的值赋值给成员变量,可以不用

 

const formData = new FormData()

formData.append("file0", this.files[0])//files[0]就是文件元素,里面有文件名,大小等属性

const xhr = new XMLHttpRequest()

xhr.open('POST','server url', true)  //server url自行填充,true代表异步

 

//发送完之后执行的函数还有其他接口可以设置比如timeout、error

xhr.onload = () => {
        const response=JSON.parse(xhr.response)//response就是服务器返回的信息
}
 

xhr.send(formData)//执行发送指令

 

或者

let config = {headers:{'Content-Type':'multipart/form-data'}}

      this.axios.post(serverUrl,
        formData, config
      ).then(res=>{
        console.log(res.data)

      }).catch(error=>{
        return false;     

})  

 

发送文件要发送form-data类型,默认的类型只能传文本

普通的post请求

//初始化post数据
let postData = this.$qs.stringify({
    action:"getinfo", 
    userID:localStorage.getItem('user_id'), 
    token:localStorage.getItem('token')
})

 

//qs的使用需要import qs from 'qs';

//qs的使用需要Vue.prototype.$qs = qs;


//执行post
this.axios({
    method:'post', 
    url:'server url', //server url自行填充
    data:postData
}).then(res=>{
    if(0 == res.data.statusCode){//服务器返回的字段,代表返回值
        localStorage.setItem('userinfo', res.data.userinfo)//服务器返回的字段,代表返回信息
    }
    else {

 

        console.log('error' + res.data.statusCode)

    }


}).catch(error=>{
    console.log('访问服务器失败')
    console.log(error)

 

 

})

 

 

//另外记录一个proxyTable的问题

proxyTable: {
     '/api': {
        target:'http://192.168.0.121'
        changeOrigin: true,
        pathRewrite: {
              '^/api': '/'
            }

     },

。。。

}

本来直接修改vue文件可以立即生效,但是修改proxyTable后没有立即生效,以为出bug,后来结束掉npm run dev,再次npm run dev就ok了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值