Django之文件上传
1:文件上传是网站中常见的功能,一般用form表单来提交:
HTML
<form action="" method="post" enctype="multipart/form-data"> <input type="file" name="myfile"> <input type="submit"> </form>
view
from django.shortcuts import render,HttpResponse from django.views.generic import View from .forms import IndexFrom class IndexView(View): def get(self,request): return render(request,"index.html") def post(self,request): myfile = request.FILES.get("myfile") //接收file文件 with open("aa.txt","wb") as fp: for chunk in myfile.chunks(): fp.write(chunk) return HttpResponse("ok")
结果会在项目目录中多了一个aa.txt文件
2:使用模型来处理上传文件
model:
class Article(models.Model): title = models.CharField(max_length=20) content = models.CharField(max_length=100) thumbnail = models.FileField(upload_to="files") //定义一个FileField字段,upload_to表示上传来的文件放在哪个文件夹也可以(upload_to="%Y%m%d")
view:
def post(self,request): title = request.POST.get("title") content = request.POST.get("content") thumbnail = request.FILES.get("myfile") //获取文件 article = Article.objects.create(title=title,content=content,thumbnail=thumbnail) article.save() return HttpResponse("ok")
3指定MEDIA_ROOT和MEDIA_URL:
在setting中添加这两个字段:
MEDIA_ROOT = os.path.join(BASE_DIR,"media") //表示长传的文件存放的目录(就可以不再upload_to中设置l) MEDIA_URL = "/media/" //访问这个文件的路径
url.py 需要设置路径:
from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path("",views.IndexView.as_view()) ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
4限制文件拓展名:
from django.db import models from django.core import validators class Article(models.Model): title = models.CharField(max_length=20) content = models.CharField(max_length=100) thumbnail = models.FileField(upload_to="%Y/%m/%d",validators=[validators.FileExtensionValidator(["txt","pdf"])]) //通过validator来限制
5上传图片:(上传图片需要安装Pillow库)(pip install Pillow)
images = models.ImageField(upload_to="files") //方法和上面一样