上傳檔案到「/」
This commit is contained in:
69
app.py
Normal file
69
app.py
Normal file
@@ -0,0 +1,69 @@
|
||||
|
||||
|
||||
import os
|
||||
from flask import Flask, request, render_template, send_from_directory, flash, redirect, url_for
|
||||
from werkzeug.utils import secure_filename
|
||||
from transform_data import process_with_rounding
|
||||
|
||||
# --- 設定 ---
|
||||
UPLOAD_FOLDER = 'uploads' # 用於儲存上傳和處理後的檔案
|
||||
ALLOWED_EXTENSIONS = {'xls', 'xlsx'}
|
||||
|
||||
app = Flask(__name__)
|
||||
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
|
||||
app.config['SECRET_KEY'] = 'supersecretkey' # Flask 需要一個密鑰來顯示提示訊息
|
||||
|
||||
# --- 輔助函式 ---
|
||||
def allowed_file(filename):
|
||||
return '.' in filename and \
|
||||
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
|
||||
|
||||
# --- 路由定義 ---
|
||||
@app.route('/', methods=['GET', 'POST'])
|
||||
def upload_file():
|
||||
if request.method == 'POST':
|
||||
# 檢查是否有上傳檔案
|
||||
if 'file' not in request.files:
|
||||
flash('沒有檔案部分')
|
||||
return redirect(request.url)
|
||||
file = request.files['file']
|
||||
# 如果使用者未選擇檔案,瀏覽器也會送出一個沒有檔名的空檔案
|
||||
if file.filename == '':
|
||||
flash('未選擇檔案')
|
||||
return redirect(request.url)
|
||||
|
||||
if file and allowed_file(file.filename):
|
||||
filename = secure_filename(file.filename)
|
||||
|
||||
# 建立上傳資料夾 (如果不存在)
|
||||
if not os.path.exists(app.config['UPLOAD_FOLDER']):
|
||||
os.makedirs(app.config['UPLOAD_FOLDER'])
|
||||
|
||||
input_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
|
||||
file.save(input_path)
|
||||
|
||||
# 產生最終檔案名稱
|
||||
base, ext = os.path.splitext(filename)
|
||||
final_filename = f"{base}_final_rounded.xlsx"
|
||||
|
||||
# 呼叫您既有的處理函式
|
||||
try:
|
||||
process_with_rounding(input_path, final_filename)
|
||||
# 提供下載連結
|
||||
return redirect(url_for('download_file', name=final_filename))
|
||||
except Exception as e:
|
||||
flash(f'處理檔案時發生錯誤: {e}')
|
||||
return redirect(request.url)
|
||||
|
||||
return render_template('index.html')
|
||||
|
||||
@app.route('/uploads/<name>')
|
||||
def download_file(name):
|
||||
return send_from_directory(app.config['UPLOAD_FOLDER'], name)
|
||||
|
||||
# --- 啟動伺服器 ---
|
||||
if __name__ == '__main__':
|
||||
# 使用 host='0.0.0.0' 讓區域網路中的其他電腦可以存取
|
||||
# 在生產環境中,建議設置 debug=False
|
||||
app.run(debug=False, host='0.0.0.0', port=12001)
|
||||
|
Reference in New Issue
Block a user