上传文件
form表单上传文件
1 <form action="/upload/" method="post" enctype="multipart/form-data">
2 {% csrf_token %}
3 头像: <input type="file" name="head-pic">
4 用户名: <input type="text" name="username">
5 <input type="submit">
6 </form>
7
8
9 def upload(request):
10 if request.method == 'GET':
11
12 return render(request,'upload.html')
13 else:
14 print(request.POST) #拿到的是post请求的数据,但是文件相关数据需要用request.FILES去拿
15 print(request.FILES) #<MultiValueDict: {'head-pic': [<InMemoryUploadedFile: 1.png (image/png)>]}>
16 file_obj = request.FILES.get('head-pic')
17 print(file_obj)
18 file_name = file_obj.name
19
20
21 # f = open('xx.txt','rb')
22 # with open('xx.txt','wb') as f2:
23 # for i in f:
24 # f2.write(i)
25 import os
26 path = os.path.join(settings.BASE_DIR,'statics','img',file_name)
27 with open(path,'wb') as f:
28 for i in file_obj:
29 f.write(i)
30 #for chunk in file_obj.chunks():
31 # f.write(chunk)
32
33 return HttpResponse('ok')
ajax上传文件
1 var formdata = new FormData();
2 formdata.append('user',$('#username').val())
3 formdata.append('csrfmiddlewaretoken',$('#csrfmiddlewaretoken').val())
4 formdata.append('file',$('#file')[0].files[0])
5 $.ajax({
6 url:'/upload/',
7 type:'post',
8 data:formdata,
9 success:function(response){
10 response
11
12 }
13
14 })
15
16 def upload(request):
17 if request.method == 'GET':
18
19 return render(request,'upload.html')
20 else:
21 print(request.POST) #拿到的是post请求的数据,但是文件相关数据需要用request.FILES去拿
22 print(request.FILES) #<MultiValueDict: {'head-pic': [<InMemoryUploadedFile: 1.png (image/png)>]}>
23 file_obj = request.FILES.get('head-pic')
24 print(file_obj)
25 file_name = file_obj.name
26
27
28 # f = open('xx.txt','rb')
29 # with open('xx.txt','wb') as f2:
30 # for i in f:
31 # f2.write(i)
32 import os
33 path = os.path.join(settings.BASE_DIR,'statics','img',file_name)
34 with open(path,'wb') as f:
35 for i in file_obj:
36 f.write(i)
37 #for chunk in file_obj.chunks():
38 # f.write(chunk)
39
40 return HttpResponse('ok')