我是前端开发的初学者,必须在 Flask 中为一个项目做一个小型 Web 应用程序。
我编写了一个 Flask 应用程序,它允许您使用 HTML 表单上传图像,然后在您点击上传时将图像显示回用户。我需要对此进行修改,以便每次用户上传图像时都不会将图像保存到项目目录中的文件夹中。基本上,应用程序应该将上传的图像发送回响应的正文中。
到目前为止,这是我的代码:
上传测试.py
import os
from uuid import uuid4
from flask import Flask, request, render_template, send_from_directory
app = Flask(__name__)
# app = Flask(__name__, static_folder="images")
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
@app.route("/")
def index():
return render_template("upload.html")
@app.route("/upload", methods=["POST"])
def upload():
target = os.path.join(APP_ROOT, 'images/')
print(target)
if not os.path.isdir(target):
os.mkdir(target)
else:
print("Couldn't create upload directory: {}".format(target))
print(request.files.getlist("file"))
for upload in request.files.getlist("file"):
print(upload)
print("{} is the file name".format(upload.filename))
filename = upload.filename
destination = "/".join([target, filename])
print ("Accept incoming file:", filename)
print ("Save it to:", destination)
upload.save(destination)
return render_template("complete.html", image_name=filename)
@app.route('/upload/<filename>')
def send_image(filename):
return send_from_directory("images", filename)
if __name__ == "__main__":
app.run(port=8080, debug=True)
upload.html - 创建一个上传表单
<!DOCTYPE html>
<html>
<head>
<title>Upload</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<form id="upload-form" action="{{ url_for('upload') }}" method="POST" enctype="multipart/form-data">
<strong>Files:</strong><br>
<input id="file-picker" type="file" name="file" accept="image/*" multiple>
<div id="msg"></div>
<input type="submit" value="Upload!" id="upload-button">
</form>
</body>
<script>
$("#file-picker").change(function(){
var input = document.getElementById('file-picker');
for (var i=0; i<input.files.length; i++)
{
var ext= input.files[i].name.substring(input.files[i].name.lastIndexOf('.')+1).toLowerCase()
if ((ext == 'jpg') || (ext == 'png'))
{
$("#msg").text("Files are supported")
}
else
{
$("#msg").text("Files are NOT supported")
document.getElementById("file-picker").value ="";
}
}
} );
</script>
</html>
complete.html - 显示用户点击“上传”后保存的文件夹中的图像
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
Uploaded
<img src=" {{url_for('send_image', filename=image_name)}}">
</body>
</html>
我已经尝试了很多研究,但除了在显示文件夹后删除文件夹之外找不到任何东西(我认为这不是解决手头问题的正确方法)。我真的很感谢在这件事上的任何帮助,如果有比我的代码当前所做的更好的解决方案,我很想了解更多!
谢谢!:)