w文件上传功能

上传文件流程

vue.js–>axios–>django接口–>file来写文件–>文件操作(可压缩文件,可同步到七牛云-又拍云)–>提取文件名称–>vue.js

上传文件vue.js

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<div>
<table>
<tr>
// Avatar 使图片展示为圆形
<Avatar :src="src" :width="150" height="150px"></Avatar>
</tr>

<tr>
<td>用户头像:</td>
//当图片发生改变是@change不是click点击
<td><input type="file" @change="upload"></td>
</tr>

</table>

</div>

// return中定义s变量

src:''


//上传文件
upload:function (e) {

//获取文件
let file = e.target.files[0];
//声明表单参数
let param = new FormData();

param.append('file',file,file.name);

//声明请求头
let config = {headers:{'Content-Type':'multipart/form-data'}};

// 发送请求
this.axios.post('http://localhost:8000/upload/',param,config).then((res)=>{

console.log(res);

//图片的路径要拼接起来
this.src = 'http://localhost:8000/static/upload/'+res.data.filename;

})

}

配置setting文件上传路径

1
2
3
4
5
6
7
8
STATIC_URL = '/static/'

STATICFILES_DIRS[
os.path.join(BASE_DIR,'static')
]

#定义文件夹
UPLOAD_ROOT = os.path.join(BASE_DIR,'static/upload')

上传文件接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os

#文件上传通用类
class UploadFile(APIView):

def post(self,request):

#接收参数
myfile = request.FILES.get('file')

#建立文件流对象
f = open(os.path.join(UPLOAD_ROOT,'',myfile.name.replace('"','')),'wb')

#写入
for chunk in myfile.chunks():
f.write(chunk)
f.close()

return Response({'filename':myfile.name.replace('"','')})
原文地址:https://www.cnblogs.com/anle123/p/13365517.html