rookiedee
rookiedee

Reputation: 3

Flask: Ignore if one file is not uploaded in form (containing multiple file upload options)

I have a multi-upload form in flask.

  <form class="form-group" action="{{ url_for('load') }}" method="POST" enctype="multipart/form-data">
   <input id="file-picker" type="file" name="file1"><br>
   <input id="file-picker" type="file" name="file2"><br>
   <input id="file-picker" type="file" name="file3"><br>
   <input id="file-picker" type="file" name="file4"><br>
  </form>

This is how i handle data from it:

@app.route("/load", methods=['GET', 'POST'])
def load():

    if request.method == 'POST':
        file = request.files.get("file1")
        file_name = secure_filename(file.filename)
        im = Image.open(file)
        im.save(file_name)
        upload(photo=file_name)

The upload() uploads the image from the form to s3.I dont want to use request.getlist('files'), because this way, retrieving them later on is easier. I save the uploaded files in a static folder before uploading them to amazon s3. If I wanted to upload only 3 out of these 4 files, I get IOError: [Errno 22].

Is there any way to ignore this error? i.e Can I make it such that I can upload only one/two/three instead of compulsorily uploading all 4 files every time?

Upvotes: 0

Views: 368

Answers (1)

rookiedee
rookiedee

Reputation: 3

All right, so here is what I did..turned out to be pretty simple. Thanks for the tip @furas

@app.route("/load", methods=['GET', 'POST'])
def load():
 if request.method == 'POST':
    files = request.files.getlist("file")
    for file in files:
       file.seek(0, os.SEEK_END)

      if file.tell() == 0:
        pass
      else:
        file_name = secure_filename(file.filename)
        upload(p=file_name)

Upvotes: 0

Related Questions