0
我想上傳圖像「camera.jpg」並將其保存到「static/photo /」目錄,然後將「camera.jpg」文件重命名爲「niloofar .jpg「文件。python - 將圖像上傳到目錄中,保存並重命名
我該怎麼做?
app.py:
from flask import Flask, request, url_for, render_template, make_response, redirect
from flask_sqlalchemy import SQLAlchemy
from werkzeug.utils import secure_filename
UPLOAD_FOLDER = '/home/me/my_flask_project/static/photo/'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://myusername:[email protected]/mydbname'
db = SQLAlchemy(app)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
@app.route('/upload/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
#return redirect(url_for('upload_file', filename=filename))
os.rename(UPLOAD_FOLDER + filename, 'niloofar.jpg')
return render_template('upload.html')
if __name__ == '__main__':
app.run()
upload.html:
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
我也試過低於這個劇本,但它甚至不將圖像保存到 「照片」 目錄:
import os, sys
@app.route('/upload/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
#return redirect(url_for('upload_file', filename=filename))
os.rename(UPLOAD_FOLDER + filename, 'niloofar.jpg')
return render_template('upload.html')
什麼是問題?
是的,謝謝:) – Andishe