使用Flask上传图像并将其作为响应显示回来

8
我是一个前端开发的初学者,必须为一个项目做一个小的 Flask 网络应用程序。
我已经编写了一个 Flask 应用程序,通过 HTML 表单让你上传图片,当你点击上传按钮时,它会将图片显示回用户。我需要对此进行修改,使得每次用户上传图片时,图片不会被保存到项目目录中的文件夹中。基本上,该应用程序应当在响应体中发送所上传的图像。
以下是我的代码:
UploadTest.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>

我尝试过做了相当多的研究,但除了在文件夹被显示后将其删除之外,我没有找到其他任何解决此问题的方法(我认为这不是正确的解决方式)。非常感激能在此事上得到任何帮助,如果有比我当前代码更好的解决方案,我很愿意学习!

谢谢!:)


用户正在发送许多文件。您想只返回一张图片还是发送多张? - Laraconda
但是我的代码只显示了最后上传的文件。我需要一次只发送一个图像,但我希望能够返回并再次上传另一个图像。@LaraChicharo - Richa Netto
我有同样的问题。两年过去了,我们还是没有答案? - hoang tran
2个回答

2
请查看以下代码,它可能会对您有帮助。将以下代码复制到“模板”文件夹中的“upload.html”中,不要更改HTML标签。
<!DOCTYPE html>

<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />

 <script src="{{ url_for('static', filename='upload.js') }}"></script>

<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
</style>
</head>
<body>
<form action = "http://127.0.0.1:5000/uploader" method = "POST" 
 enctype = "multipart/form-data">
  <input type='file' name = 'file' onchange="readURL(this);" />
    <img id="blah" src="#" alt="your image" />
 <input type = "submit"/>
</form>
</body>
</html>

将以下代码复制到static文件夹中的upload.js文件中。

function readURL(input) {
if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
        $('#blah')
            .attr('src', e.target.result)
            .width(150)
            .height(200);
    };

    reader.readAsDataURL(input.files[0]);
}
}

现在将以下代码复制到Python文件中。
from flask import Flask, render_template, request
from werkzeug import secure_filename
import os 

app = Flask(__name__)

app.config['UPLOAD_FOLDER'] = 'D:/Projects/flask/image_upload/images/'

@app.route('/')
def upload_f():
   return render_template('upload.html')

@app.route('/uploader', methods = ['GET', 'POST'])
def upload_file():
   if request.method == 'POST':
      f = request.files['file']
      f.save(os.path.join(app.config['UPLOAD_FOLDER'],secure_filename(f.filename)))
      return 'file uploaded successfully'

# if __name__ == '__main__':
app.run(debug = True)

上面的代码将帮助您在HTML页面上浏览和显示图像,并将图像保存到所需位置。


0

如果你想将图片发送回客户端,有两种方法:

  1. 您可以将图像作为文件 URL 发送给客户端
  2. 您需要将图像转换为 Blob 或 Base64 图像并显示图像

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接