首页 > 解决方案 > 通过 Flask 上传多个图像并在 JSON 中存储列表

问题描述

这是我通过 Python Flask 上传多个图像的地方(这一切都很好,因为所有选定的图像都上传并保存到具有正确名称类型的正确文件夹等)。问题是将上传的图像列表保存到 JSON 中。到目前为止,我有它,其中 JSON 中的值是一个列表,它将一个图像名称保存到列表中,但似乎不能循环遍历其他图像名称来保存其他图像名称?我也不确定 Python 文件中 storyTimeMap 函数中的 .split 是否正确,我在另一个项目中使用过它并且在这里使用它有意义吗?任何帮助表示赞赏

主要 Python 文件:

def storyTimeMap(form, filename):
    storyTime = {}
    storyTime["Title"] = form["Title"]
    storyTime["ParaOne"] = form["StoryPara"]
    storyTime["ParaTwo"] = form["StoryParaTwo"]
    storyTime["ParaThree"] = form["StoryParaThree"]
    storyTime["ParaFour"] = form["StoryParaFour"]
    storyTime["Quote"] = form["Quote"]
    storyTime["schoolSelect"] = form["schoolSelect"]
    storyTime["filename"] = filename.split()
    return storyTime

@app.route("/textupload/", methods=['GET','POST'])
def text():
    if request.method == "POST":
        if 'filename' not in request.files:
            flash("No Image Uploaded, Try Again")
            return redirect(request.url)
        file = request.files['filename']
        if file.filename == '':
            flash("No File Selected, Try Again")
            return refirect(request.url)
        if file and allowed_file(file.filename):
            for f in request.files.getlist("filename"):
                f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename))
                print "THIS IS MULIPLE IMAGES?"
                print f.filename
            # filename = secure_filename(file.filename)
            # file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    if request.method == "POST" and "Title" in request.form:
        data[request.form["Title"]] = storyTimeMap(request.form, f.filename)
        with open('/var/www/FlaskApp/FlaskApp/newstories.json', 'w') as outfile:
            json.dump(data, outfile)
        flash("Your Story Has Been Posted!")
        return render_template("main.html", data=data, filename=filename)
    return render_template("textupload.html", data=data)

HTML表格:

{% extends "header.html" %}

{% block body %}
<body>

<div class="container">
<h3>Upload a Story!</h3>
<form method=post enctype=multipart/form-data>
  <fieldset>
      <input type = "text" class = "form-control" placeholder = "Story Title" name="Title">
      <p></p>
      <textarea  type ="text" class ="form-control" placeholder ="Paragragh One" name="StoryPara" rows = "3"></textarea>
      <p></p>
      <textarea type ="text" class ="form-control" placeholder ="Paragragh Two" name="StoryParaTwo" rows = "3"></textarea>
      <p></p>
      <textarea type ="text" class ="form-control" placeholder ="Paragragh Three" name="StoryParaThree" rows = "3"></textarea>
      <p></p>
      <textarea type ="text" class ="form-control" placeholder ="Paragragh Four" name="StoryParaFour" rows = "3"></textarea>
      <p></p>
      <p>School:</p>
      <select class="form-control" name="schoolSelect">
        <option>School of Computing</option>
        <option>School of Engineering and Built Environment</option>
        <option>School of Business</option>
        <option>School of Applied Sciences</option>
        <option>School of Arts and Creative Industries</option>
        <option>School of Health and Social Care</option>
      </select>
      <p></p>
      <input type="text" class="form-control" placeholder="Quote" name="Quote">
      <p></p>
      <input type=file name=filename multiple>
      <p></p>
      <input class="btn btn-default" type="Submit" value="Submit">
      <p></p>
    <a href="/admin" class="btn btn-secondary" role="button">Admin Page</a>
  </fieldset>
</form>
</div>
</body>
{% endblock %}

JSON FILE(文件名是一个列表,但只存储一个文件名):

{
 "TEST TEN MULTI": {
    "ParaFour": "hfswrthwrth",
    "ParaOne": "ADGEQRG",
    "ParaThree": "srthbsfghwrt",
    "ParaTwo": "ADFGADFS",
    "Quote": "whshrrssth",
    "Title": "TEST TEN MULTI",
    "filename": [
      "bart-simpson_c_200x200.png"
    ],
    "schoolSelect": "School of Computing"
  },
  "VERSION 3": {
    "ParaFour": "qefgkljenglkqejrn",
    "ParaOne": "sdkjcah alight dskjhv kljabds",
    "ParaThree": "reqlifhdskljgnekrlg",
    "ParaTwo": "vadfgdfkghiausdnv",
    "Quote": "radgfdwguahflkjdsn",
    "Title": "VERSION 3",
    "filename": "HomeFuels-Direct-truck-200x200.png",
    "schoolSelect": "School of Computing"
  }
}

标签: pythonjsonlistflask

解决方案


text处理函数中循环遍历图像时,您可以将文件名保存在列表中,并将该列表作为参数传递给您的storyTimeMap函数。像这样的东西:

def text():
    if request.method == "POST":
        if 'filename' not in request.files:
            flash("No Image Uploaded, Try Again")
            return redirect(request.url)
        file = request.files['filename']
        if file.filename == '':
            flash("No File Selected, Try Again")
            return refirect(request.url)
        if file and allowed_file(file.filename):
            file_list = []
            for f in request.files.getlist("filename"):
                file_list.append(f.filename)
                f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename))
                print "THIS IS MULIPLE IMAGES?"
                print f.filename

然后您可以在调用storyTimeMap函数时传递列表:

data[request.form["Title"]] = storyTimeMap(request.form, file_list)

目前,您似乎只是将最后一张图片的名称传递给您的storyTimeMap函数。这就解释了为什么您在列表中只得到一个文件名。

然后不要这样做:

storyTime["filename"] = filename.split()

您可以像这样分配列表:

storyTime["filename"] = file_list

推荐阅读