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
原文地址:https://www.cnblogs.com/polly-ling/p/9593506.html