django文件上传

django上传文件,可直接通过form表单的input type='file'上传,也可构造一个模型通过模型的FileField字段上传。

1.通过form表单直接上传文件

def form(req):
    if req.method == 'GET':
        return render(req,'form.html')
    else:
        file = req.FILES.get('file')
        print(file,file.name,file.size)
        with open(os.path.join('static',file.name),'wb') as f: #在static目录下创建同名文件
            for line in file.chunks():
                f.write(line) #逐行读取上传的文件内容并写入新创建的同名文件
        return HttpResponse('welcome')
处理form表单的函数
<form action="form" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <p>姓名 <input type="text" name="user"></p>
    <p>文件 <input type="file" name="file"></p>
    <p><input type="submit"></p>
</form>
form表单模型

①对于上传文件,在后台通过file = req.FILES.get('file')获取,而在前端,form表单中需要指定参数enctype="multipart/form-data"

②对于获取到的file文件,file.name和file.size表示文件的名称和大小

③以上只是获取到文件,还需要上传到本地服务器,以上从with到f.write的三行表示在static目录下创建同名文件,逐行读取文件内容并写入。

        

单独使用类型为file的input框,显示效果不佳,未选则文件时选择框右侧会有提示“未选择任何文件”如上图1,可利用a标签、定位和透明度自定义上传标签,如上图三。

<div style="position: relative">
    <a style="border: gray solid 1px">选择文件</a>
    <input type="file" name="file" style="opacity: 0.5;position: absolute;left: 0">
</div>

2.通过模型的FileField字段上传文件

#模型
class UploadForm(forms.Form):
    user = fields.CharField(label='姓名')
    file = fields.FileField(label='文件')

#处理函数
def model(req):
    if req.method =='GET':
        obj = UploadForm()
        return render(req, 'model.html',{'obj':obj})
    else:
        obj = UploadForm(req.POST,req.FILES)
        if obj.is_valid():
            file = obj.cleaned_data['file']  #获取文件
            print(file,file.name,file.size)
            with open(file.name,'wb') as f:
                for line in file.chunks():
                    f.write(line)
            return HttpResponse('ok')
        else:
            return HttpResponse('fail')
创建模型和处理函数
<form action="model" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <table>
        {{ obj.as_table }}
    </table>
    <input type="submit">
</form>
模型
原文地址:https://www.cnblogs.com/Forever77/p/10902624.html