简体   繁体   English

从网站以python将图像写入文件

[英]Writing image to file in python from website

I wrote this code: 我写了这段代码:

class uploadfromfile:
    def POST(self, name=None):
            filename = ''.join(random.choice('abcdefghijklmnopqrstuvwxyz') for i in range(20))
            x = web.input(upfile={})
            f = open(filename, 'w')
            f.write(x['upfile'].value)
            f.close()
            imgFromFile(filename)
            return "some html"

But it doesn't work. 但这是行不通的。 I get a huge error that ends with this: UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 15: invalid start byte 我收到一个以此结尾的巨大错误:UnicodeDecodeError:'utf8'编解码器无法解码位置15的字节0xff:无效的起始字节

The error appears to arrive at f.write(x['upfile'].value), and I can't for the life of me figure out why. 错误似乎出现在f.write(x ['upfile']。value)上,我一生都无法找出原因。 Any ideas what is going wrong? 任何想法出了什么问题? I know that the value is in that variable, because if I just return it the image displays in my browser. 我知道值在那个变量中,因为如果我只返回它,图像就会显示在浏览器中。

The first thing I can see wrong with the code is that the file isn't opened in binary mode. 我首先看到的代码错误是该文件未以二进制模式打开。 When reading at writing files that aren't simple strings, binary mode is required to treat the data as nothing more than bytes. 在读取不是简单字符串的文件时,需要使用二进制模式将数据视为字节。 Simply switch the file opening like to f = open(filename, 'wb') to resolve that issue. 只需将文件打开方式切换为f = open(filename, 'wb')即可解决该问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM