gpt4 book ai didi

python - 当文件小于1kByte时,cStringIO.StringO无法保存上传的文件流

转载 作者:行者123 更新时间:2023-12-01 04:35:14 24 4
gpt4 key购买 nike

我借用了这段代码来将文件流保存到磁盘,它可以工作,除非文件大小小于 1kb。我收到此错误:

in stuff_uploaded:
copy(theFile.file.name, './tmp/'+theFile.filename) #saves temporary file to /cp2/tmp/

AttributeError:“cStringIO.StringO”对象没有属性“name”

@cherrypy.expose
@cherrypy.tools.noBodyProcess()
def stuff_uploaded(self, theFile=None):
import cgi
import tempfile
# convert the header keys to lower case
lcHDRS = {key.lower():val for key, val in cherrypy.request.headers.iteritems()}
class myFieldStorage(cgi.FieldStorage):
"""uses a named temporary file instead of the default non-named file; keeping it visibile (named), allows us to create a
2nd link after the upload is done, thus avoiding the overhead of making a copy to the destination filename."""
def make_file(self, binary=None):
return tempfile.NamedTemporaryFile()
formFields = myFieldStorage(fp=cherrypy.request.rfile,
headers=lcHDRS,
environ={'REQUEST_METHOD':'POST'},
keep_blank_values=True)
theFile = formFields['theFile']
# we now create a 2nd link to the file, using the submitted filename.
from shutil import copy
copy(theFile.file.name, './tmp/'+theFile.filename) #saves temporary file
msgs = csv_to_survey.match_fieldnames('./tmp/'+theFile.filename)
return './tmp/'+theFile.filename

那么我该怎么做才能确保 cStringIO.StringO 处理上传的小文件呢?

最佳答案

直接打开并写入文件:

with open('./tmp/'+theFile.filename, "w") as f:
f.write(theFile.file.getvalue())

或者无论文件是在磁盘上还是StringIO上都可以处理它,将其用作类似文件的对象:

import shutil

with open('./tmp/'+theFile.filename, "w") as f:
# If the file pointer might not be at the beginning of theFile.file, add:
# theFile.file.seek(0)
shutil.copyfileobj(theFile.file, f)
# While:
# f.write(theFile.file.read())
# would work most of the time, it involves holding the whole contents of the
# file in memory at once (which you want to avoid; that's why CherryPy
# uses temp files for larger data). shutil.copyfileobj does block by
# block copies, which have fixed peak memory usage while still running
# (almost) as fast

注意:这(以及您的原始解决方案)是不安全的,因为上传同一文件两次将覆盖以前的文件,并且(取决于名称上的服务器过滤器)文件名可能会遍历文件系统以覆盖 tmp 之外的意外文件目录。

关于python - 当文件小于1kByte时,cStringIO.StringO无法保存上传的文件流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31813856/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com