django基础之文件上传

一:前端实现

  1. 在前端中,需要填入一个form标签,然后在这个form标签中指定enctype=“multipart/form-data”,不然就不能上传文件。
  2. 在form标签中添加一个input标签,然后指定input标签的name,以及type=“file”。

以上两步的示例代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="uploadFile">
    <input type="submit" name="提交">
</form>
</body>
</html>

二:后端实现

后端的主要工作是接收文件。然后存储文件。接收文件的方式跟接收POST的方式是一样的,只不过是通过FILES来实现。

from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import View
class IndexView(View):
    def get(self, request):
        return render(request, "index.html")
    def post(self, request):
        file = request.FILES.get("uploadFile")
        with open("save.txt", "wb") as fp:
            for chunk in file.chunks():
                fp.write(chunk)
        return HttpResponse("success")

以上代码通过request.FILES接收到文件后,再写入到指定的地方。这样就可以完成一个文件的上传功能了

三:使用模型来处理上传的文件

在定义模型的时候,可以给存储文件的字段指定为FileField,这个Field可以传递一个upload_to参数,用来指定上传上来的文件保存到哪里。
比如将其保存到当前项目的files文件夹下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
    <input type="text" name="title">
    <input type="text" name="content">
    <input type="file" name="uploadFile">
    <input type="submit" name="提交">
</form>
</body>
</html>
# models.py
class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    thumbnail = models.FileField(upload_to="files") 
    # 指定上传的位置,和setting.py的MEDIA_ROOT有关,如果MEDIA_ROOT没有设置,为当前项目的指定目录
# views.py
def index(request):
    if request.method == 'GET':
        return render(request,'index.html')
    else:
        title = request.POST.get('title')
        content = request.POST.get('content')
        thumbnail = request.FILES.get('thumbnail')
        article = Article(title=title, content=content, thumbnail=thumbnail)
        article.save()
        return HttpResponse('success')

调用完article.save()方法,就会把文件保存到files下面,并且会将这个文件的路径存储到数据库中

四:指定MEDIA_ROOT和MEDIA_URL来指定上传文件存储的路径

上面表单的字段是使用了upload_to来指定上传的文件的目录。
也可以指定MEDIA_ROOT,就不需要在FielField中指定upload_to,他会自动的将文件上传到MEDIA_ROOT的目录下

MEDIA_ROOT = os.path.join(BASE_DIR,'media')  # 当前项目的media文件
# 类似static, 127.0.0.0.1/media/ 访问
MEDIA_URL = '/media/'

然后可以在urls.py中添加MEDIA_ROOT目录下的访问路径

from django.urls import path
from front import views
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    path('', views.index),
] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

如果同时指定MEDIA_ROOT和upload_to,那么会将文件上传到MEDIA_ROOT下的upload_to文件夹中

class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    thumbnail = models.FileField(upload_to="%Y/%m/%d/")

五:限制上传的文件拓展名

如果想要限制上传的文件的拓展名,那么我们就需要用到表单来进行限制。我们可以使用普通的Form表单,也可以使用ModelForm,直接从模型中读取字段。

必须注意表单里的字段名是模型的字段,更是模板的input标签的name

# models.py
class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    thumbnial = models.FileField(upload_to='%Y/%m/%d/',validators=[validators.FileExtensionValidator(['txt','pdf'])])  # 添加一个过滤器
# forms.py
class ArticleForm(forms.ModelForm):
    class Meta:
        model = Article
        fields = "__all__"
# views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import View
from .forms import ImageForm
from .models import Article
class IndexView(View):
    def get(self, request):
        return render(request, "index.html")
    def post(self, request):
        form = ImageForm(request.POST, request.FILES)  #注意写法
        if form.is_valid():
            form.save()
            return HttpResponse("success")
        else:
            print(form.errors.get_json_data())
            return HttpResponse("failure")

六:上传图片

注意:使用ImageField,必须要先安装Pillow库

pip install Pillow

上传图片跟上传普通文件是一样的。只不过是上传图片的时候Django会判断上传的文件是否是图片的格式(除了判断后缀名,还会判断是否是可用的图片)。如果不是,那么就会验证失败。
必须注意表单里的字段名是模型的字段,更是模板的input标签的name
定义一个包含ImageField的模型。

class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    thumbnail = models.ImageField(upload_to="%Y/%m/%d/")

因为要验证是否是合格的图片,需要用一个表单来进行验证。表单直接就使用ModelForm就可以了

class MyForm(forms.ModelForm):
    class Meta:
        model = Article
        fields = "__all__"

版权声明:本文为pcn01原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。