Search code examples
filepython-3.xbottle

Python ValueError: I/O operation on closed file, files saves with no data


I have a form like this:

<form action="/test-upload" method="post" enctype="multipart/form-data">
      <input type="file" name="upload" />
  <input type="submit" name="submit" value="Start upload" />
</form>

And I have a function like this:

@route("/test-upload")
@post("/test-upload")
def test_upload():
    if request.POST.get("submit"):
        f = request.POST.get("upload")

        upload_path = "uploaded_files/{0}".format(f.filename)
        f.save(upload_path, overwrite=True)
        return "ok"
    return template("test_upload")

Which results in the following error:

File "/usr/lib/python3.4/site-packages/bottle.py", line 2389, in save
     self._copy_file(fp, chunk_size)
   File "/usr/lib/python3.4/site-packages/bottle.py", line 2367, in _copy_file
     read, write, offset = self.file.read, fp.write, self.file.tell()
 ValueError: I/O operation on closed file

If I change to this, I get the same error as above:

    f.save("uploaded_files", overwrite=True)

If I use either of these:

        with open(upload_path, 'w') as open_file:
             open_file.write(f.file.read())

or

        with open(upload_path, 'wb') as open_file:
            open_file.write(f.file.read())

I this error:

open_file.write(f.file.read())
 ValueError: read of closed file

What's confusing is that something does save to the file system, with the proper extension (I've tested jpeg and pdf), there is no data in any of the files. I just don't see what, if anything, I am doing wrong with either version. I'm looking to upload a file with data.

I'm using Python3.4 with bottle.

some things I've looked at: How to upload and save a file using bottle framework

and: http://bottlepy.org/docs/dev/tutorial.html#file-uploads


Solution

  • try

    f = request.files.get('upload') # .files, not .post
    f.save(upload_path)
    

    Edit: #567 In python 3.4 multipart file upload breaks due to change in cgi.FieldStorage

    but it should be fixed. can you try updating your bottle version to the last one?