臨近過年,一個人太無聊 了,遇到的問題就想想怎么解決
flask之大文件下載
- 起因公司因為新切網絡,沒法共享測試版本(十個G左右),公司兩個辦公區域,A區可以非常麻溜的下載版本,B區網絡幾KB每秒。B區下不到版本,又要版本刷機完成測試任務,很是煩惱,沒招就把手機從B拿到A刷機,一堆手續,很是費勁; 就想自己用flask在A起個服務 然后通過網頁傳輸下載;代碼如下
# pycharm 社區版 沒法直接創建一個flask項目 都是手敲寫的
# app.py
import os
from flask import Flask, Response, render_template
app = Flask(__name__)
@app.route('/')
def hello_world():
fileNames=[]
obj = os.walk("static")
for root,dirname,filename in obj:
fileNames.append(filename)
return render_template("index.html",fileNames=fileNames[0])
@app.route("/download/<filename>")
def download(filename):
# 普通下載
store_path = "./static/"+filename
return send_from_directory(store_path, filename, as_attachment=True)
if __name__ == '__main__':
app.run(
host="192.168.1.128",
port="5000",
debug=True
)
#index.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3個meta標簽*必須*放在最前面,任何其他內容都*必須*跟隨其后! -->
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<style>
</style>
</head>
<body>
<h1>何慶青資源</h1>
{% for file in fileNames %}
<a href="/download/{{ file }}">下載:{{ file }}</a>
{% endfor %}
</body>
<script>
</script>
</html>
#需要下載的資源放static里
- 上面實現了,也可以下載了;但是遇到一個問題,大文件怎么也下載不下來。神奇一批;經過研究查閱,是send_from_directory這個方法沒法傳輸太大文件,傳輸到一定大小又停止重新傳輸,導致大文件沒法傳輸;然后改善下載代碼如下,成功解決
def download(filename):
# 流式讀取
def send_file():
store_path = "./static/"+filename
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