Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

Gray-Ice

个人博客兼个人网站

Vue代码:

页面代码(其中input框并不需要):

1
2
3
4
<div id='upload'>
拖拽上传
<input type="file" @change='yp_upload'>
</div>
methods中的代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
onDrag(e){
e.stopPropagation();
e.preventDefault();
},
onDrop(e){
e.stopPropagation();
e.preventDefault();
// 通用自定义上传方法
this.yp_upload(e.dataTransfer.files);
},
// 又拍云拖拽上传
yp_upload:function(files){
// 获取拖拽文件
let file = files[0];
// 声明参数
let param = new FormData();
param.append('file', file);
param.append('username', localStorage.getItem('username'))
// 声明头部信息
const headers = {
'Content-Type': 'multipart/form-data'
};
// 发送请求
this.axios.post('http://127.0.0.1:8000/youpai/', param).then(res=>{
console.log(res)
})
},

mounted中的代码:

1
2
3
4
5
6
7
8
// 获取最新的token
this.get_token();
// 注册拖拽容器
let upload = document.querySelector('#upload');
// 声明监听事件
upload.addEventListener('dragenter', this.onDrag, false);
upload.addEventListener('dragover', this.onDrag, false);
upload.addEventListener('drop', this.onDrop, false);

后台Python代码(使用Django框架):

Views.py中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import upyun
from rest_framework.response import Response
from rest_framework.views import APIView


class YouPai(APIView):

def post(self, request):
# 接收参数
myfile = request.FILES.get('file', None)
# 判断是否收到参数
if myfile:
up = upyun.UpYun('应用名称', '管理员名称', '管理员密钥', endpoint=upyun.ED_AUTO)
with open('./forup/' + myfile.name, 'wb') as f:
for chunk in myfile.chunks():
f.write(chunk)
# 流式传输
with open('./forup/' + myfile.name, 'rb') as f:
res = up.put('/image/' + myfile.name, f, checksum=False)
return Response({
'msg': '上传成功',
'type': res['file-type']
})
return Response({'msg': '文件接收失败'})

urls.py中:

1
path('youpai/', YouPai.as_view(), name='youpai'),

评论



愿火焰指引你