Django下载文件

今天写代码的时候有个需求,要下载xlsx文件到本地,浏览器直接访问路径不可以,就要单独写个方法,返回包含文件数据的响应头。

from django.http import HttpRequest,FileResponse
from django.utils.encoding import escape_uri_path
from django.template import RequestContext
from codecs import open
import os

def download(request,kwargs):
 fileurl = request.GET['fileurl']
 filename = os.path.split(fileurl)[1]
 file = open('kingWeb' +fileurl,'rb')
 response = FileResponse(file)
 response['Content-Type'] = 'application/octet-stream'
 response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path(filename))
 return response
#使用 url/adm/home/download?fileurl=/upload/temp/20180706/201807062313.xlsx
#浏览器即可提示下载文件
#escape_uri_path方法是为了将中文文件名转换为url编码
#不然浏览器会读取不到文件名
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇