前端
<template>
<div>
<tr>
<td>又拍云上传:</td>
<td>
<div id="upload">
拖拽上传
</div>
<input type="file" @change="upload_upyun">
</td>
</tr>
</div>
</template>
<script>
export default{
data(){
return{
}
},
//监听属性
watch:{
},
//计算属性
computed:{
},
mounted :function() {
let upload = document.querySelector('#upload');
upload.addEventListener('dragenter', this.onDrag, false);
upload.addEventListener('dragover', this.onDrag, false);
upload.addEventListener('drop', this.onDrop, false);
},
//自定义方法
methods:{
onDrag(e){
e.stopPropagation();
e.preventDefault();
},
onDrop(e){
e.stopPropagation();
e.preventDefault();
// 判断是否有文件
this.upload_upyun(e.dataTransfer.files)
},
upload_upyun:function(files){
// 获取参数
let file = files[0];
let param = new FormData();
//声明参数
param.append('file',file)
//指定类型
const config = {
headers: {'Content-Type': 'multipart/form-data'}
}
// 这里是声明一下this 有时候在axios里获取不到this属性
var a = this
// 上传图片
a.axios.post('http://localhost:8000/youpai/',param,config).then(function(response){
console.log(response)
})
}
}
}
</script>
<style>
#upload {
margin: 100px auto;
width: 300px;
height: 150px;
border: 2px dashed #f00;
padding-top: 50px;
padding-left: 80px;
}
</style>
后端
#定义文件上传类
class YouPai(View):
def post(self,request):
# 获取图片
img = request.FILES.get('file')
# 生成独特的文件名
filename = make_password(img.name) + str((int(round(time.time() * 1000)))) + ".jpg"
# 实例化对象
up = upyun.UpYun('md233',username='wangrui',password='7Ly7NfX30PQ63GyPFIlSIHiQ2QRWQz76')
headers = { 'x-gmkerl-quality': '50' }
# 分块上传
for chunk in img.chunks():
res = up.put('/%s'%filename,chunk,checksum=True,headers=headers)
return JsonResponse({'filename':filename})