python - 将图像上传到目录,保存并重命名

时间:2016-08-17 08:17:44

标签: python file upload save rename

我想上传图片" camera.jpg"并将其保存到"静态/照片/"目录然后重命名" camera.jpg"提交给" niloofar.jpg"文件。

我该怎么做?

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:mypassword@localhost/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>

我也在下面尝试过这个脚本,但它甚至没有将图像保存到&#34;照片&#34;目录:

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')

有什么问题?

1 个答案:

答案 0 :(得分:3)

尝试在os.rename中提供完整的目标路径。

os.rename(UPLOAD_FOLDER + filename, UPLOAD_FOLDER+'niloofar.jpg')