Django上传文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/upload.html" method="POST" enctype="multipart/form-data">
        <input type="text" name="file_name">
        <div style="position: relative">
            <a>点击上传文件</a>
            <input type="file" name="is_file" style="opacity: 0;position: absolute;top: 0;left: 0;">
        </div>
        <input type=submit name="OK">
    </form>
</body>
</html>
from django.shortcuts import render,HttpResponse

# Create your views here.

def upload(request):
    if request.method == "GET":
        return render(request,"upload.html")
    else:
        #print(request.POST)   #<QueryDict: {'file_name': ['12321321'], 'OK': ['提交']}>
        #print(request.FILES)  #<MultiValueDict: {'is_file': [<TemporaryUploadedFile: 说明书.pdf (application/pdf)>]}>

        filename = request.POST.get("file_name")
        isfile = request.FILES.get("is_file") #isfile是对象(内容有文件大小,文件名称,文件内容等)

        print(isfile.name,isfile.size)   #isfile.name文件名   #isfile.size文件大小,可以拿这值做限制

        f = open('file/'+isfile.name,'wb')
        for data in isfile.chunks():
            f.write(data)
        f.close()
        return HttpResponse("ok")

猜你喜欢

转载自www.cnblogs.com/ajaxa/p/9884086.html