之前jquery异步上传文件时用的uploadify,但毕竟这是面向过程基于节点的插件,如果前端使用vue.js的脚手架,就要入乡随俗,利用vue.js自带的vue-resource来实现异步上传视频文件
首先安装 vue-resource 没必要全局安装,所以只在需要用到的项目中安装即可
cnpm install vue-resource --save
如果安装报错就把后面 --save去掉
如果你的vue是脚手架项目就在main.js中引入并且声明使用
我是在index.js引入的,感觉都一样
//引入resource
import VueResource from 'vue-resource'
//声明使用
Vue.use(VueResource)
然后在vue组件里写代码实现
<template>
<div id="uploads">
<input type="file" @change="getFile($event)" /><button @click="upload">上传</button>
<div>{{ result }}</div>
<div v-show="uping==1">正在上传中</div>
<div v-show='result'>
<video ref='video' controls>
您的浏览器不支持 video元素。
</video>
<!-- 上传图片专用 -->
<!-- <img :src="img" width="500px"> -->
</div>
</div>
</template>
现在是上传视频,如果上传图片就把图片专用注释打开,它是专门为显示上传成功后的图片占的位置, video 是用来显示视频的
然后在vue.js中写绑定方法,定义变量
<script>
export default{
name:"uploads",
data:function(){
return{
upath: '',
result: '',
uping:0,
img:''
}
},
methods:{
// 将上传的文件传参过来 对upath进行绑定赋值,此时upath就不在是空值了
getFile: function (even) {
this.upath = event.target.files[0];
},
upload: function () {
var zipFormData = new FormData();
// 将文件放进zipFormData 容器了,逗号前面是key,后面是value
zipFormData.append('file', this.upath);//filename是键,file是值,就是要传的文件
// 传输文件一定要加上这个type headers
let config = { headers: { 'Content-Type': 'multipart/form-data' } };
this.uping = 1;
this.axios.post('/api/uploadmp4/', zipFormData,config).then(response=> {
console.log(response);
console.log(response.data);
this.uping = 0;
this.result = response.data.message;
//上传图片
// this.img = response.data.url
//绑定播放地址 response.data.url是后台保存视频的路径
this.$refs.video.src = response.data.url;
});
}
}
}
</script>
最后,写一下后端上传代码:
import os
# 上传文件
class Uploadmp4(APIView):
def post(self,request):
item = {}
file = request.FILES.get('file')
f = open(os.path.join(settings.STATICS_IMG,'',file.name),'wb')
#写文件 遍历文件流
for chunk in file.chunks():
f.write(chunk)
item['message'] = '上传成功'
item['url'] = 'http://127.0.0.1:8000/static/images/'+ file.name
item['error'] = 0
return Response(item,content_type='application/json')
到此就可以做到异步上传文件功能,可是体验试试