Django文件上传

2021-04-07 05:27

阅读:459

YPE html>

标签:cut   isp   ane   tle   mit   relative   div   html   dmi   

一、普通上传方式

技术图片技术图片
 1 
 2 "en">
 3 4     "UTF-8">
 5     Title 6 
 7 
 8 
"/upload.html" method="post" enctype="multipart/form-data"> 9 {% csrf_token %} 10

"file" name="uploadFile">

11 15
16 17
HTML
技术图片技术图片
 1 from django.shortcuts import render
 2 from django.shortcuts import redirect
 3 from django.shortcuts import HttpResponse
 4 import os
 5 
 6 # Create your views here.
 7 from django import forms
 8 from django.forms import fields
 9 
10 class myForm(forms.Form):
11     uploadFile=fields.FileField(required=True)
12 
13 def upload(request):
14     if request.method=="GET":
15         return render(request,"upload.html")
16     else:
17         uploadFile=request.FILES.get("uploadFile")
18         f=open(os.path.join(C:/Users/Administrator/PycharmProjects-forWork/Django_upload/static/img,uploadFile.name),"wb")
19         for i in uploadFile.chunks():
20             f.write(i)
21         f.close()
22         return HttpResponse("上传完成")
view函数

二、Form上传方式

技术图片技术图片
 1 
 2 "en">
 3  4     "UTF-8">
 5     Title 6 
 7 
 8 
"/upload.html" method="post" enctype="multipart/form-data"> 9 {% csrf_token %} 10

"file" name="uploadFile">

11 15
16 17
HTML
技术图片技术图片
 1 from django.shortcuts import render
 2 from django.shortcuts import redirect
 3 from django.shortcuts import HttpResponse
 4 import os
 5 
 6 # Create your views here.
 7 from django import forms
 8 from django.forms import fields
 9 
10 class myForm(forms.Form):
11     uploadFile=fields.FileField(required=True)
12 
13 def upload(request):
14     if request.method=="GET":
15         return render(request,"upload.html")
16     else:
17         obj=myForm(request.POST,request.FILES)
18         if obj.is_valid():
19             uploadFile=obj.cleaned_data["uploadFile"]
20             f=open(os.path.join(C:/Users/Administrator/PycharmProjects-forWork/Django_upload/static/img,uploadFile.name),"wb")
21             for i in uploadFile.chunks():
22                 f.write(i)
23             f.close()
24             return HttpResponse("上传完成")
25         else:
26             return HttpResponse("上传失败")
view函数

 

Django文件上传

标签:cut   isp   ane   tle   mit   relative   div   html   dmi   

原文地址:https://www.cnblogs.com/sun-10387834/p/12490157.html


评论


亲,登录后才可以留言!