Muoi
Muoi

Reputation: 13

Cannot handle files when using "input webkitdirectory" with Flask

I want to use webkitdirectory to let user upload multiple files of a folder. When I try search for a specific file by its name to analyze it in app.py, it doesn't work.

This is my HTML code

{% extends "layout.html" %} {% block title %} Home {% endblock %}
{% block main %}
<div>
  <h2>Add your data</h2>
  <form action="/analyze" method="post" enctype="multipart/form-data">
    <div class="mb-3">
      <input type="file" id="folderUpload" name="files" class="form-control" webkitdirectory multiple>
    </div>
    <button type="submit" class="btn btn-primary">Upload</button>
  </form>
</div>
{% endblock %}

And this is my python code in app.py

@app.route("/analyze", methods=["POST"])
def analyze():
    if request.method == "POST":
        # Check if the file was uploaded
        if "files" not in request.files or not request.files["files"].filename:
            return apology("no file uploaded", 400)

        search_history_file = None
        files = request.files.getlist("files")
        for file in files:
            if file.filename == "your_search_history.json":
                search_history_file = file
                break

        if search_history_file is None:
            return "your_search_history.json not found", 400

        # Generate the chart using the JSON file
        chart_data = generate_searched_text_chart(search_history_file)
        return render_template("analyze.html", chart_data=chart_data)

When I tried uploading files including "your_search_history.json", it showed "your_search_history.json not found" on the screen. After that I wrote a test function like this in app.py to print out all the files' names in order to see why I cannot find "your_search_history.json":

@app.route("/test", methods=["POST"])
def test():
    files = request.files.getlist("files")
    filesname = []
    for file in files:
        filesname += file.filename
    return render_template("test.html", filesname=filesname)

The result1 The result2

It turned out that the files' names are sent with single characters, which made me cannot find the file I need by its name. Eventhough I think I found the problem, I still don't know how to fix it.

How can I find and draw a chart based on a file named "your_search_history.json" in the files sent by the user. I really appreciate if you can give me a help. Thank you in advance.

Upvotes: 0

Views: 21

Answers (0)

Related Questions