在我的应用程序中,我将图像上传到文件夹,但是我不知道如何将它们从表单重命名为其他名称
这是我的.py
import os
from flask import Flask, render_template, request
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
@app.route("/")
def index():
return render_template("upload.html")
@app.route("/upload", methods=['GET','POST'])
def upload():
target = os.path.join(APP_ROOT, 'images/')
print(target)
if not os.path.isdir(target):
os.mkdir(target)
for file in request.files.getlist("file"):
print(file)
filename = file.filename
destination = "/".join([target, filename])
print(destination)
file.save(destination)
return render_template("complete.html")
if __name__ == "__main__":
app.run(port=4555, debug=True)
这是我的.html 显然输入type =“ text”对我不起作用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Upload here</h1>
<form id="upload-form" action="{{url_for('upload')}}" method="POST" enctype="multipart/form-data">
<input type="file" name="file" accept="image/*" multiple></br>
New name for image<input type="text">
<input type="submit" value="send">
</form>
</body>
</html>
答案 0 :(得分:1)
for file in request.files.getlist("file"):
print(file)
filename = file.filename
destination = "/".join([target, filename])
print(destination)
file.save(destination)
在此处设置包含新文件名的文件的目的地。您将filename设置为file.filename-本质上是要保留文件名。
要重命名文件,您可以像这样覆盖文件名:
filename = "myfile.jpg"
这可能是动态的,例如:
# keep extension for later
extension = filename.split()[-1]
current_dt = datetime.datetime(
new_filename = "upload-{}.{}".format(
time.time(), extension
)
这会将文件另存为:1574685161.690482.jpg