文件上传请求
一、上传文件。
1、定义一个类型为 file 的 input 标签。
2、在 input 标签中添加名为 changeHandler 的 @change 事件。
3、在 changeHandler 方法内用 this.file 对象接收上传的 File 文件。
changeHandler(e){ // 打印文件 console.log(e.target.files[0]); // 接收文件 this.file = e.target.files[0]; }
二、、发送请求。
1、在 button 发送请求按钮中添加点击事件 sandAjax。
2、在 sandAjax 方法中将接收到的 file 文件进行处理,并发送到后台服务。
3、在sandAjax 中创建一个 FormData 对象,调用该对象中的 append("文件名", 文件) 方法将文件添加到 FormData 对象中。
FormData 接口的append() 方法 会添加一个新值到 FormData 对象内的一个已存在的键中,如果键不存在则会添加该键。FormData.set 和 append() 的区别在于,如果指定的键已经存在, FormData.set 会使用新值覆盖已有的值,而 append() 会把新值添加到已有值集合的后面。
// 配置基础URL this.$axios.defaults.baseURL = 'http://127.0.0.1:8888/'; // 创建表单对象 FormData var fd = new FormData(); // 将新值 this.file 添加到 FormData 表单对象中 fd.append('file',this.file);
4、调用 axios 对象的 post 方法发送请求,并使用请求配置中的 onUploadProgress 对上传进度进行处理。
// 发送请求 this.$axios.post('upload',fd,{ // 上传进度条 onUploadProgress:(progressEvent)=>{ // 对原生进度事件处理 console.log(progressEvent); // 上传进度的值 = (文件当前上传的值/文件总值)X 100 var progress = (progressEvent.loaded/progressEvent.total)*100; console.log(progress); // 更新 DOM this.$nextTick(function(){ // 记录文件上传的进度,并实时更新 this.rate = Math.ceil(progress); }) },
}) .then(res=>{ console.log(res); }) .catch(err=>{ console.log(err); })
完整代码如下:
<script type="text/javascript">
var App = {
template:`
<div>
选择文件:{{rate}}%
上传进度:
<input type="file" name='file' @change='changeHandler' />
<button @click='sendAjax'>发送请求</button>
</div>
`,
data(){
return{
file:{},
rate:0
}
},
methods:{
sendAjax(){
// 配置基础URL
this.$axios.defaults.baseURL = 'http://127.0.0.1:8888/';
// 创建表单对象 FormData
var fd = new FormData();
// 将新值 this.file 添加到 FormData 表单对象中
fd.append('file',this.file);
// 发送请求
this.$axios.post('upload',fd,{
// 上传进度条
onUploadProgress:(progressEvent)=>{
// 对原生进度事件处理
console.log(progressEvent);
// 上传进度的值 = (文件当前上传的值/文件总值)X 100
var progress = (progressEvent.loaded/progressEvent.total)*100;
console.log(progress);
// 更新 DOM
this.$nextTick(function(){
// 记录文件上传的进度,并实时更新
this.rate = Math.ceil(progress);
})
},
})
.then(res=>{
console.log(res);
})
.catch(err=>{
console.log(err);
})
},
changeHandler(e){
console.log(e.target.files[0]);
this.file = e.target.files[0];
}
}
}
// 将axios挂载到Vue对象上
Vue.prototype.$axios = axios
new Vue({
el:'#app',
template:`
<App/>
`,
components:{
App
}
});
</script>
浙公网安备 33010602011771号