Windows 下 web.py上传图片乱码的解决办法

来源:互联网 发布:车载数据监控系统 编辑:程序博客网 时间:2024/06/05 08:05

今天在Windows平台下用web.py搭了个服务器,接收上传的图片并存储,参考的是官方cookbook里的示例代码:

def POST(self):        x = web.input(myfile={})        filedir = '/path/where/you/want/to/save' # change this to the directory you want to store the file in.        if 'myfile' in x: # to check if the file-object is created            filepath=x.myfile.filename.replace('\\','/') # replaces the windows-style slashes with linux ones.            filename=filepath.split('/')[-1] # splits the and chooses the last part (the filename with extension)            fout = open(filedir +'/'+ filename,'w') # creates the file where the uploaded file should be stored            fout.write(x.myfile.file.read()) # writes the uploaded file to the newly created file.            fout.close() # closes the file, upload complete.        raise web.seeother('/upload')

然后在服务器端打开存储的图片,是大片大片的色块,完全不能用,一定是编码出问题了,网上搜了一下,参考豆瓣里这个帖子,把
fout = open(filedir +'/'+ filename,'w')
替换成
fout = open(filedir +'/'+ filename,'wb')

问题就解决了。

原来,Windows下默认的写入是按照字符来写入的,而我们的图片是2进制的,所以在文件的打开方式参数里用‘b’来说明按照2进制来写入,问题就解决了。

0 0
原创粉丝点击