• 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")   //方法和上面一样
  • 相关阅读:
    双飞翼布局和圣杯布局的对比
    阿里云centos+java环境搭建
    Android零散知识点积累
    [转]linux shell 流程控制(条件if,循环【for,while】,选择【case】语句实例
    [转]linux shell 获取当前正在执行脚本的绝对路径
    [转+整理]linux shell 将字符串分割成数组
    [转]linux shell 数组建立及使用技巧
    linux shell 入门
    jquery 字符串转为json
    JQuery插件开发入门
  • 原文地址:https://www.cnblogs.com/yan-peng/p/10271960.html
Copyright © 2020-2023  润新知