Flask框架編寫文件下載接口過程講解
方式一
@app.route("/download1") def download(): # return send_file('test.exe', as_attachment=True) return send_file('2.jpg') # return send_file('1.mp3')
如果不加as_attachment參數(shù),則會向瀏覽器發(fā)送文件,比如發(fā)送一張圖片:
發(fā)送mp3
加上as_attachment參數(shù),則會下載文件。
方式二
通過Response來實現(xiàn)
部分代碼如下:
@app.route("/download2") def download2(): file_name = "1.jpg" #https://www.runoob.com/http/http-content-type.html response = Response(file_send(file_name), content_type='image/jpeg') response.headers["Content-disposition"] = f'attachment; filename={file_name}' return response
其中content-type要根據(jù)文件的具體類型來設(shè)置,具體參考如下常見的:
content-type(內(nèi)容類型),一般是指網(wǎng)頁中存在的 content-type,用于定義網(wǎng)絡(luò)文件的類型和網(wǎng)頁的編碼,決定瀏覽器將以什么形式、什么編碼讀取這個文件,content-type 標(biāo)頭告訴客戶端實際返回的內(nèi)容的內(nèi)容類型。
常見的媒體格式類型如下:
- text/html : HTML格式
- text/plain :純文本格式
- text/xml : XML格式
- image/gif :gif圖片格式
- image/jpeg :jpg圖片格式
- image/png:png圖片格式
- application/xhtml+xml :XHTML格式
- application/xml: XML數(shù)據(jù)格式
- application/atom+xml :Atom XML聚合格式
- application/json: JSON數(shù)據(jù)格式
- application/pdf:pdf格式
- application/msword : Word文檔格式
- application/octet-stream : 二進制流數(shù)據(jù)(如常見的文件下載)
- application/x-www-form-urlencoded : 中默認(rèn)的encType,form表單數(shù)據(jù)被編碼為key/value格式發(fā)送到服務(wù)器(表單默認(rèn)的提交數(shù)據(jù)的格式)
完整代碼
app.py
from flask import Flask,send_file,Response from flask_cors import CORS app = Flask(__name__) CORS(app,resources={r"/*": {"origins": "*"}},supports_credentials=True) @app.route("/download1") def download(): # return send_file('test.exe', as_attachment=True) # return send_file('2.jpg') return send_file('1.mp3') # filefold file # return send_from_directory('./', 'test.exe', as_attachment=True) # send big file def file_send(file_path): with open(file_path, 'rb') as f: while 1: data = f.read(20 * 1024 * 1024) # per 20M if not data: break yield data @app.route("/download2") def download2(): file_name = "1.jpg" response = Response(file_send(file_name), content_type='image/jpeg') response.headers["Content-disposition"] = f'attachment; filename={file_name}' return response if __name__ == '__main__': app.config['JSON_AS_ASCII'] = False app.run(debug=True)
到此這篇關(guān)于Flask框架編寫文件下載接口過程講解的文章就介紹到這了,更多相關(guān)Flask文件下載內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python正則表達式re.match()匹配多個字符方法的實現(xiàn)
這篇文章主要介紹了python正則表達式re.match()匹配多個字符方法的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01關(guān)于Python中浮點數(shù)精度處理的技巧總結(jié)
雙精度浮點數(shù)(double)是計算機使用的一種數(shù)據(jù)類型,使用 64 位(8字節(jié)) 來存儲一個浮點數(shù)。下面這篇文章主要給大家總結(jié)介紹了關(guān)于Python中浮點數(shù)精度處理的技巧,需要的朋友可以參考借鑒,下面來一起看看吧。2017-08-08keras實現(xiàn)VGG16方式(預(yù)測一張圖片)
這篇文章主要介紹了keras實現(xiàn)VGG16方式(預(yù)測一張圖片),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07