Django View

1. HttpResponse

http.py

 def _read_file(file_name, buffer_size):
    f = open(file_name, "rb")
    while True:
        c = f.read(buffer_size)
        if c:
            yield c
        else:
            break
    f.close()


def down_file(file_name, download_file_name='download.file', content_type='APPLICATION/OCTET-STREAM', buffer_size=1024):
    response = HttpResponse(_read_file(file_name, buffer_size), content_type=content_type);
    response['Content-Type'] = 'application/octet-stream; charset=utf-8'
    response['Content-Disposition'] = 'attachment; filename={0}'.format(download_file_name)
    return response

views.py

def out_odt(requesest,name):
template = webodt.ODFTemplate('test.odt')
context = dict(name=name)
document = template.render(Context(context))
base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
output_path = os.path.join(base_path,'_webodt','outputs','out.odt')
with open(output_path,'w') as f:
    f.write(document.read())
    f.close()

return down_file(output_path)

下载文件,自定义返回类型
没办法用中文名,等待hack

response['Content-Disposition'] = 'attachment; filename={0}'.format(download_file_name.encode('UTF-8'))

download_file_name进行urlencode只在个别浏览器起效