Django文件的上传与下载

文件上传部分,直接上代码:

def uploadfile(request): #上传文件
    if request.method == 'POST':
        handle_uploaded_file(request.FILES.getlist("myfile",None))
        return HttpResponse("文件上传成功")
 
    return HttpResponse("Failed")

def handle_uploaded_file(files):
    if not os.path.exists('upload/'):
        os.mkdir('upload/')
    for file in files:
        # print file.name 
        with open('upload/' + file.name, 'wb+') as destination:
            for chunk in file.chunks():
                destination.write(chunk)

接收前端post过来的filelist,将其一一以二进制方式写入到新文件中。

至于文件下载,我选用打包成zip文件的方式,这需要用到zipfile模块,所以要

import zipfile

正式代码如下:

def downloadzipfile(request):
    rootdir = 'download'
    the_file_name = "yourzip.zip" 
    z = zipfile.ZipFile(the_file_name, 'w',zipfile.ZIP_DEFLATED)
    for parent,dirnames,filenames in os.walk(rootdir):
        for file in filenames:
            z.write(rootdir + os.sep + file)
    z.close()        
    response = StreamingHttpResponse(file_iterator(the_file_name))
    response['Content-Type'] = 'application/zip'
    response['Content-Disposition'] = 'attachment; filename=yourzip.zip'
    return response 

def file_iterator(file_name, chunk_size=512):
    with open(file_name, 'rb') as f:
        while True:
            c = f.read(chunk_size)
            if c:
                yield c
            else:
                break   

可将Django项目目录下download文件夹里的文件打包为zip文件,并下载到本地,使用StreamingHttpResponse比HttpResponse更适合于文件的传输,不会因文件过大导致占用内存过大而崩溃。

有时文件有中文名会有bug,这种时候需要将代码修改为如下模样:

from django.utils.encoding import escape_uri_path
from django.http import HttpResponse
def test(request):
    file_name = '测试.txt'
    content = ...
    response = HttpResponse(content, content_type='application/octet-stream')
    response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path(file_name))
    return response

Python文件打开方式:

 r : 以只读方式打开文件,文件不存在则出错

 w:以只写方式打开文件,文件存在则清空,不存在则建立

 a:以追加只写的方式打开,不清空文件,在文件末尾加入内容  

+: 有读写双权限。

r只有读的权限,w和a只有写的权限,w清空文件,a不清空文件。(read, write,append)

转载于:https://my.oschina.net/u/2277123/blog/804449

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值