在Python3中保存上传文件时出现问题

时间:2010-10-02 06:15:46

标签: file-upload python-3.x

我控制了网络中POST方法上传的数据问题。  如果文件是文本没有问题,但当它是一个编码文件,作为图片或其他文件时,麻烦来了。系统何时将数据插入文件中的内容。 好吧,它没有以正确的方式编码。我将把所有代码从区域中取出environ ['wsgi.input']到保存文件的区域:

# Here the data from the environ['wsgi.input'], 
# first i convert the byte into a string delete the first 
# field that represent the b and after i strip the single quotes
tmpData = str(rawData)[1:].strip("' '")
dat = tmpData.split('\\r')#Then i split all the data in the '\\r'
s = open('/home/hidura/test.png', 'w')#I open the test.png file.
for cont in range(5,150):#Now beging in the 5th position to the 150th position
s.write(dat[cont])#Insert the piece of the data in the file.
s.close()#Then closed.

错误在哪里?

提前谢谢你。

1 个答案:

答案 0 :(得分:1)

为什么要将二进制数据转换为字符串? png文件二进制数据。只需将二进制数据写入文件即可。您还需要以二进制模式打开文件。

s = open('/home/hidura/test.png', 'wb')
s.write(data)