flask下載文件---文件流


html:
<a name="downloadbtn" class="btn btn-success pull-right" href="/downloadfile/?filename=/root/allfile/123.txt">下載</a>

py:

@app.route('/downloadfile/', methods=['GET', 'POST'])

def downloadfile():
if request.method == 'GET':
fullfilename = request.args.get('filename')
    # fullfilename = '/root/allfile/123.txt'

fullfilenamelist = fullfilename.split('/')
filename = fullfilenamelist[-1]
filepath = fullfilename.replace('/%s'%filename, '')
#普通下載
# response = make_response(send_from_directory(filepath, filename, as_attachment=True))
# response.headers["Content-Disposition"] = "attachment; filename={}".format(filepath.encode().decode('latin-1'))
#return send_from_directory(filepath, filename, as_attachment=True)
#流式讀取
def send_file():
store_path = fullfilename
with open(store_path, 'rb') as targetfile:
while 1:
data = targetfile.read(20 * 1024 * 1024) # 每次讀取20M
if not data:
break
yield data

response = Response(send_file(), content_type='application/octet-stream')
response.headers["Content-disposition"] = 'attachment; filename=%s' % filename # 如果不加上這行代碼,導致下圖的問題
return response
沒有文件名,和文件格式,遇到這種情況,打開F12,查看response.headers 與正常的比較










免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM