使用python的Flask框架進(jìn)行上傳和下載文件詳解
send_file()函數(shù):
def send_file( path_or_file: t.Union[os.PathLike, str, t.BinaryIO], mimetype: t.Optional[str] = None, as_attachment: bool = False, download_name: t.Optional[str] = None, attachment_filename: t.Optional[str] = None, conditional: bool = True, etag: t.Union[bool, str] = True, add_etags: t.Optional[bool] = None, last_modified: t.Optional[t.Union[datetime, int, float]] = None, max_age: t.Optional[ t.Union[int, t.Callable[[t.Optional[str]], t.Optional[int]]] ] = None, cache_timeout: t.Optional[int] = None, ):
參數(shù)解析:
- path_or_file:要發(fā)送的文件的路徑,如果給出了相對(duì)路徑,則相對(duì)于當(dāng)前工作目錄?;蛘撸远M(jìn)制模式打開的類文件對(duì)象。確保將文件指針查找到數(shù)據(jù)的開頭。
- mimetype:為文件發(fā)送的MIME類型。如果沒有提供,它將嘗試從文件名檢測(cè)它。
- as_attachment:指示瀏覽器應(yīng)該提供給保存文件而不是顯示它。
- download_name:瀏覽器保存文件時(shí)使用的默認(rèn)名稱。默認(rèn)為傳遞的文件名。
- conditional:基于請(qǐng)求頭啟用條件響應(yīng)和范圍響應(yīng)。需要傳遞一個(gè)文件路徑和``environ``。
- etag:計(jì)算文件的etag,這需要傳遞一個(gè)文件路徑。也可以是字符串來代替。
- last_modified:發(fā)送文件的最后修改時(shí)間,單位為秒。如果沒有提供,它將嘗試從文件路徑檢測(cè)它。
- max_age:客戶端應(yīng)該緩存文件多長(zhǎng)時(shí)間,以秒為單位。如果設(shè)置,' ' Cache-Control ' '將為' ' public ' ',否則將為' ' no-cache ' '以選擇條件緩存。
注意:
示例代碼:
import os from flask import Flask, send_file, request, render_template, redirect from werkzeug.utils import secure_filename app = Flask(__name__) UPLOAD_FOLDER = 'media' # 注意:要提前在根目錄下新建media文件,否則會(huì)報(bào)錯(cuò) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER # 判斷上傳的文件是否是允許的后綴 def allowed_file(filename): return "." in filename and filename.rsplit('.', 1)[1].lower() in set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) @app.route('/') def index(): return "hello world!" @app.route('/generate_file') def generate_file(): with open('./new_file.txt', 'w', encoding='utf-8') as f: f.write('我是new_file.txt文件!') return "<./new_file.txt>文件已經(jīng)生成!" @app.route('/download') def download(): return send_file('./new_file.txt', as_attachment=True) @app.route('/upload', methods=['GET', 'POST']) def upload(): if request.method == 'GET': return render_template('upload.html') else: if "file" not in request.files: return redirect(request.url) file = request.files.get('file') # 獲取文件 # 上傳空文件(無文件) if file.filename == '': return redirect(request.url) if file and allowed_file(file.filename): if not os.path.exists(f'./templates/{UPLOAD_FOLDER}'): os.mkdir(f'./templates/{UPLOAD_FOLDER}') filename = secure_filename(file.filename) # 用這個(gè)函數(shù)確定文件名稱是否是安全 (注意:中文不能識(shí)別) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) # 保存文件 return "上傳文件成功!" if __name__ == '__main__': app.run()
下載和上傳路徑中可以添加用戶身份驗(yàn)證:
import os from flask import Flask, send_file, request, render_template, redirect from werkzeug.utils import secure_filename app = Flask(__name__) UPLOAD_FOLDER = 'media' # 注意:要提前在根目錄下新建media文件,否則會(huì)報(bào)錯(cuò) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER allow_users = ['dgw', 'super_user'] # 判斷上傳的文件是否是允許的后綴 def allowed_file(filename): return "." in filename and filename.rsplit('.', 1)[1].lower() in set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) @app.route('/') def index(): return "hello world!" @app.route('/generate_file') def generate_file(): with open('./new_file.txt', 'w', encoding='utf-8') as f: f.write('我是new_file.txt文件!') return "<./new_file.txt>文件已經(jīng)生成!" @app.route('/download') def download(): user_name = request.args.get('user_name') if not user_name: return "你沒有權(quán)限下載文件!" if user_name and user_name not in allow_users: return "你沒有權(quán)限下載文件!" return send_file('./new_file.txt', as_attachment=True) @app.route('/upload/<string:user_name>', methods=['GET', 'POST']) def upload(user_name): if request.method == 'GET': if user_name not in allow_users: return "您沒有權(quán)限訪問此頁面!" return render_template('upload.html') else: if user_name not in allow_users: return "您沒有權(quán)限訪問此頁面!" if "file" not in request.files: return redirect(request.url) file = request.files.get('file') # 獲取文件 # 上傳空文件(無文件) if file.filename == '': return redirect(request.url) if file and allowed_file(file.filename): if not os.path.exists(f'./templates/{UPLOAD_FOLDER}'): os.mkdir(f'./templates/{UPLOAD_FOLDER}') filename = secure_filename(file.filename) # 用這個(gè)函數(shù)確定文件名稱是否是安全 (注意:中文不能識(shí)別) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) # 保存文件 return "上傳文件成功!" if __name__ == '__main__': app.run()
附錄:
upload.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Upload</title> </head> <body> <form action="" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="上傳"> </form> </body> </html>
到此這篇關(guān)于使用python的Flask框架進(jìn)行上傳和下載文件詳解的文章就介紹到這了,更多相關(guān)python的Flask框架上傳下載內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python使用PySimpleGUI打造輕量級(jí)計(jì)算器
PySimpleGUI是一個(gè)跨平臺(tái)的Python GUI庫,它支持Windows、Mac和Linux等多種操作系統(tǒng),本文將利用PySimpleGUI打造一個(gè)輕量級(jí)計(jì)算器,希望對(duì)大家有所幫助2024-03-03Python機(jī)器學(xué)習(xí)庫Scikit-learn實(shí)戰(zhàn)教程
文章介紹了Python在機(jī)器學(xué)習(xí)領(lǐng)域的應(yīng)用,重點(diǎn)介紹了Scikit-learn庫的使用方法,并通過實(shí)際案例展示了如何使用Scikit-learn進(jìn)行分類、回歸、聚類和文本挖掘等任務(wù),同時(shí),文章還討論了特征工程、超參數(shù)調(diào)整、避免過擬合和交叉驗(yàn)證等進(jìn)階技巧2025-01-01python使用PIL模塊實(shí)現(xiàn)給圖片打水印的方法
這篇文章主要介紹了python使用PIL模塊實(shí)現(xiàn)給圖片打水印的方法,涉及使用PIL模塊操作圖片的相關(guān)技巧,需要的朋友可以參考下2015-05-05python matplotlib 繪圖 和 dpi對(duì)應(yīng)關(guān)系詳解
這篇文章主要介紹了python matplotlib 繪圖 和 dpi對(duì)應(yīng)關(guān)系詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-03-03python numpy庫np.percentile用法說明
這篇文章主要介紹了python numpy庫np.percentile用法說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-06-06python基于雙向鏈表實(shí)現(xiàn)LFU算法
這篇文章主要為大家詳細(xì)介紹了python基于雙向鏈表實(shí)現(xiàn)LFU算法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-05-05python linecache 處理固定格式文本數(shù)據(jù)的方法
今天小編就為大家分享一篇python linecache 處理固定格式文本數(shù)據(jù)的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-01-01Python中工廠模式的實(shí)現(xiàn)小結(jié)
工廠模式是一種創(chuàng)建型設(shè)計(jì)模式,通過定義一個(gè)工廠類,將對(duì)象的實(shí)例化過程封裝起來,本文主要介紹了Python中工廠模式的實(shí)現(xiàn)小結(jié),具有一定的參考價(jià)值,感興趣的可以了解一下2023-11-11