Python ValueError:对已关闭文件的I / O操作,文件保存时没有数据

时间:2016-02-25 10:50:12

标签: file python-3.x bottle

我有一个这样的表格:

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

我有这样的功能:

@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")

导致以下错误:

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

如果我改为这个,我会得到与上面相同的错误:

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

如果我使用以下任何一种:

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

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

我这个错误:

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

令人困惑的是,某些东西会保存到文件系统,并且具有适当的扩展名(我已经测试过jpeg和pdf),任何文件中都没有数据。我只是看不出是什么,如果有的话,我对这两个版本做错了。我想上传一个包含数据的文件。

我正在使用带有瓶子的Python3.4。

我看过的一些事情:How to upload and save a file using bottle framework

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

1 个答案:

答案 0 :(得分:1)

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

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

但应该修复。 你能尝试将瓶子版本更新到最后一个版本吗?