Django实现文件的上传

Django实现文件的上传

1、前端页面:使用file对象,读取文件对象传递到views中。需要设定enctype="multipart/form-data",表明不对字符进行编码。

<body>
    <form method="POST" action="." enctype="multipart/form-data">
     <p align="center">
         <span> 请选择docx文件,默认是xx.docx:</span>
        <input type="file" name="docxfile"/>
        <input type="submit" value="提交"/>
     </p>
</body>

2、在views.py中的处理函数,使用chunks()方法

def file_upload(request):  # 选择docx文件,并显示在页面
    if request.method == "GET":
        return render(request, 'file_upload.html')
    elif request.method == "POST":
        obj = request.FILES.get('filename')#FILES的对象 
        if obj:
            #print(obj, obj.name)
            file_path = os.path.join('upload', obj.name) #上传文件的路径+文件名
            f = open(file_path, mode="wb") #打开文件对象
            for i in obj.chunks(): #使用chunks()方法读取数据,写入文件
                f.write(i)
            f.close()
        else:
            file_path = os.path.join('upload', 'xxxxxx.docx')#默认文件
        file_str = read_docxfile(file_path)#读取docx文件,传到前端页面显示
    return render(request, 'file_upload.html', {'file_str': file_str})
原文地址:https://www.cnblogs.com/sdlyxyf/p/10608526.html