File upload 在Python3中保存上载的文件时出现问题

File upload 在Python3中保存上载的文件时出现问题,file-upload,python-3.x,File Upload,Python 3.x,我控制通过POST方法在web中上传的数据的问题。 如果文件是文本,没有问题,但当它是一个编码文件,如图片或其他文件时,麻烦就来了。当系统将数据插入到文件中时会发生什么。 它的编码方式不对。我将把所有的代码,从whats take the environ['wsgi.input']区域放到保存文件的区域: # Here the data from the environ['wsgi.input'], # first i convert the byte into a string delete

我控制通过POST方法在web中上传的数据的问题。 如果文件是文本,没有问题,但当它是一个编码文件,如图片或其他文件时,麻烦就来了。当系统将数据插入到文件中时会发生什么。 它的编码方式不对。我将把所有的代码,从whats take the 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.
错在哪里


提前谢谢。

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

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