flask上傳文件到指定路徑


flask上傳文件到指定路徑

項目結構如下:

首先是:視圖函數uload_file.py,代碼如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import Flask,render_template,request,redirect,url_for
from werkzeug.utils import secure_filename
import os

app = Flask(__name__)

@app.route('/upload', methods=['POST', 'GET'])
def upload():
    if request.method == 'POST':
        f = request.files['file']
        basepath = os.path.dirname(__file__)  # 當前文件所在路徑
        print(basepath)
        upload_path = os.path.join(basepath, 'upload_file_dir',secure_filename(f.filename))
        # 注意:沒有的文件夾一定要先創建,不然會提示沒有該路徑
        print(upload_path)
        upload_path = os.path.abspath(upload_path) # 將路徑轉換為絕對路徑
        print(upload_path)
        f.save(upload_path)
        return redirect(url_for('upload'))
    return render_template('upload.html')


if __name__ == '__main__':
    app.run(debug=True)

 

然后是html模板:upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>文件上傳示例</h1>
    <form action="" enctype='multipart/form-data' method='POST'>
        <input type="file" name="file">
        <input type="submit" value="上傳">
    </form>
</body>
</html>

 

 

最后可以發現已經成功上傳

 


免責聲明!

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



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