结果展示:
settings配置
STATIC_URL = '/static/'
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'video_khd/static'),
]
# 定义上传文件夹的路径
UPLOAD_ROOT = os.path.join(BASE_DIR, 'video_khd/static/upload')
文件配置
配置完成后在自己所规定的目录下创建static文件,在static文件下创建upload文件
前端vue简单代码
<template>
<div>
<!-- 上传文件 -->
<span style="margin-left:20%;">上传文件:</span>
<van-uploader class="uploader" :before-read="beforeRead" multiple />
<!-- 视频展示 -->
<video class="uploadvideo" controls autoplay :src='src'></video>
</div>
</template>
<script>
export default {
data(){
return{
src:'',
filename: '',
filesize: '',
filetotol: '',
filenumber: 1,
}
},
methods:{
beforeRead(file){
// 获取文件名
this.filename=file.name,
// 获取文件大小 当上传出现异常情况时用于兜底处理,我们需要知道文件的大小从而在缓存中对文件进行修复
this.filesize=file.size,
// 获取文件切片的总数 按照每片2M进行切片
this.filetotol=Math.ceil(this.filesize/(1024*1024))
alert(this.filesize)
// 进行切片操作
this.afterRead(file)
},
afterRead(file){
console.log(file)
var data = new FormData()
// 将分片信息存入dat中
data.append('filename',this.filename)
data.append('filesize',this.filesize)
data.append('filetotol',this.filetotol)
data.append('filenumber',this.filenumber)
// 规定单分片起始位置
var start = (this.filenumber-1)*1024*1024
// 规定单分片结束位置
var end = (this.filenumber)*1024*1024
// 将文件按照起始结束进行分片
var uploadfile = file.slice(start,end)
data.append('file',uploadfile)
// alert('开始上传')
this.$axios.post('uploadfile/',data)
.then(resp=>{
if(resp.data.code==200){
console.log(resp)
this.src = resp.data.url
// alert(this.src)
// alert('上传完毕')
}else{
this.filenumber++;
this.afterRead(file)
// alert('上传中')
}
})
}
}
}
</script>
<style>
.uploadvideo{
width: 90%;
height: 100%;
margin-top: 5%;
margin-left: 5%;
}
.uploader{
margin-top: 25%;
}
</style>
后端views代码
class FileUploadView(APIView):
def post(self,request):
data = request.data
filename = data['filename']
filesize = int(data['filesize'])
filetotol = data['filetotol']
filenumber = data['filenumber']
files = request.FILES.get('file')
filearr = filename.split('.')
with open('./video_khd/static/upload/' + filearr[0] + "_" +str(filenumber),'wb') as f:
for chunk in files.chunks():
f.write(chunk)
if int(filetotol) == int(filenumber):
# 合并
with open('./video_khd/static/upload/'+ filename,'wb') as f:
for i in range(int(filetotol)):
ufilename = "./video_khd/static/upload/"+ filearr[0] + '_' + str(i+1)
with open(ufilename, 'rb') as chunk:
f.write(chunk.read())
# 删除分片文件
os.remove(ufilename)
return Response({'code':200,'url':'http://127.0.0.1:8000/static/upload/'+filename})
else:
return Response({'code':100020})