• Django--文件上传和下载,自测试可用


    html

     
    千万注意form 中要指定enctype="multipart/form-data" 不然get就是一个None.


    <div class="form-group col-sm-offset-2 col-sm-10"> <label for="exampleInputFile">File input</label> <input type="file" name="fi" id="exampleInputFile"> <br> </div>

    views

    上传

    def up_file(request):
        if request.method == "GET":
            return render(request, "up_file.html")
    
    
        if request.method == "POST":
            # if request.user.is_anonymous():
            #     return redirect('/login')
            srf_nu = request.POST.get('srf_nu')
            start_date = request.POST.get('start_date')
            receivce_date = request.POST.get('receivce_date')
            myfile = request.FILES.get('fi')
    
            if not myfile:
                return HttpResponse("no files for upload!")
    
            destination = open(os.path.join("static",myfile.name), 'wb+')
            for chunk in myfile.chunks():
                destination.write(chunk)
            destination.close()
            Srf.objects.create(srf=srf_nu,file_path='static/%s'%myfile.name,createdate=start_date,recedate=receivce_date)
            return redirect('/labsmith/checklist')

    下载

    def download(request):
        filename = request.GET.get(u'file')
        name=filename.split('/')[1]
        file = open(filename,mode='rb')
        response=FileResponse(file)
        response['Content-Type']='application/octet-stream'
        response['Content-Disposition']='attachment;filename="%s'%name
        return response
  • 相关阅读:
    机器学习的数学基础
    Numpy + matplotlib + pandas 用法示例
    笔记:《ZeroMQ》
    Bash 常用快捷键
    Python网络爬虫
    Bash-Script 应用案例
    Bash-Script 语法详解
    ADB的使用
    ROS概述
    架构风格
  • 原文地址:https://www.cnblogs.com/polly-ling/p/9593506.html
Copyright © 2020-2023  润新知