Python 正在重命名上载的文件
在我的应用程序中,我正在将图像上传到一个文件夹中,但我不知道如何将它们从表单重命名为其他内容 这是我的Python 正在重命名上载的文件,python,flask,Python,Flask,在我的应用程序中,我正在将图像上传到一个文件夹中,但我不知道如何将它们从表单重命名为其他内容 这是我的 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("u
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>
头衔
上传到这里
图像的新名称
在这里,您可以为包含新文件名的文件设置目标。您将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
# keep extension for later
extension = filename.split()[-1]
current_dt = datetime.datetime(
new_filename = "upload-{}.{}".format(
time.time(), extension
)