情况是这样的:
我使用PIL处理图像,然后将其保存到StringIO对象。现在,我想通过poster发布StringIO对象。但是,我无法获得request.FILES字典中的图像。我在谷歌上搜索了几个小时,我发现了这个问题,python : post data within stringIO through poster?我试过了,但不起作用。
所以,我读了发帖的源代码,发现它试图获取类文件对象参数的'name‘属性,但似乎StringIO对象没有'name’属性,所以,filename和filetype都是None
if hasattr(value, 'read'):
# Looks like a file object
filename = getattr(value, 'name', None)
if filename is not None:
filetype = mimetypes.guess_type(filename)[0]
else:
filetype = None
retval.append(cls(name=name, filename=filename,
filetype=filetype, fileobj=value))
else:
retval.append(cls(name, value))因此,我指定了StringIO对象的名称属性,它看起来很好用。
im_tmp = Image.open(StringIO(bits))
//bits: the binary chars of a image
im_res = ImageAPI.process(im_tmp, mode, width, height)
//ImageAPI: a class that use PIL methods to process image
output = StringIO()
im_res.save(output, format='PNG')
output.name = 'tmp.png'
//I add above code and it works
call(url_str=url, file_dict={'file':output})
//call: package of poster我做得对吗?通过poster发布StringIO对象的正确方式是什么?
发布于 2013-07-15 16:33:10
根据this commit的说法,显式地将名称设置为可选是为了支持传入StringIO对象,但正如您所发现的那样,这样就跳过了对mime类型的检测,并将其默认为text/plain。
那么,你的方法是完全正确的。只需设置.name属性以促使poster检测mime类型。
另一种选择是使用更好的库来发布到web上。我建议你看看requests,它开箱即用,包括一种设置文件名的方法。如果传入,mimetype将基于显式文件名。
https://stackoverflow.com/questions/17649453
复制相似问题