zoukankan      html  css  js  c++  java
  • django文件上传

    views.py

    from django.shortcuts import render,HttpResponse
    import random
    from upload import settings
    # Create your views here.
    
    # def upload(request):
    #     if request.method == "POST":
    #         file_obj = request.FILES.get("upload")
    #         print(file_obj.name,)
    #         with open(file_obj.name,'wb') as f:
    #             for line in file_obj.chunks():
    #                 f.write(line)
    #                 return HttpResponse("上传成功")
    #     return render(request,"upload.html")
    
    def upload(request):
        if request.method == "POST":
            file_obj = request.FILES.get("upload")
            print(file_obj.name)
            # file_name = file_obj.name.rsplit(".",maxsplit=1)[0] + str(random.randint(0,100000))+'.'+file_obj.name.rsplit(".",maxsplit=1)[1]
            # print(file_name)#存在static/media/img文件夹下
            fname = '%s/img/%s' % (settings.MEDIA_ROOT, file_obj.name)
            with open(fname,'wb') as f:
                for line in file_obj.chunks():
                    f.write(line)
                    return HttpResponse("上传成功")
        return render(request,"upload.html")

    upload.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    
    <form action="/upload/" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <span>文件上传:</span>
        <input type="file" name="upload">
        <input type="submit" value="提交">
    </form>
    
    
    </body>
    </html>

    setting.py

    MEDIA_ROOT=os.path.join(BASE_DIR,"static/media")

    存在static/media/img文件夹下

  • 相关阅读:
    Linux内核配置过程
    Linux内核最顶层文档
    LeetCode 11月第2周题目汇总
    Chapter0
    序列加法的讨论
    ch2-基本工具介绍
    ch1-数据科学概述
    在Linux下制作Linux&windows启动盘
    VMware Workstation 与 Device/Credential Guard 不兼容?
    Linux mint 19.3配置CUDA+安装Tensorflow
  • 原文地址:https://www.cnblogs.com/chvv/p/10369464.html
Copyright © 2011-2022 走看看