2013-03-17 103 views
0

使用BottlePy,我使用下面的代码上传文件并将其写入到磁盘:文件写入到磁盘中的蟒蛇3.X

upload = request.files.get('upload') 
raw = upload.file.read() 
filename = upload.filename 
with open(filename, 'w') as f: 
    f.write(raw) 
return "You uploaded %s (%d bytes)." % (filename, len(raw)) 

它返回的字节适量的每一次。

上传工作正常文件一样.txt.php.css ...

但它导致了其他文件损坏的文件中像.jpg.png.pdf.xls ...

我试着改变open()功能

with open(filename, 'wb') as f: 

它返回以下错误r:

TypeError('must be bytes or buffer, not str',)

我猜它与二进制文件有关的问题?

是否有什么要安装在Python之上,以运行任何文件类型的上传?


更新

只是可以肯定,通过@thkang指出,我试着用bottlepy的开发版本和内置方法.save()

upload = request.files.get('upload') 
upload.save(upload.filename) 
实现代码

它返回完全相同的异常错误

TypeError('must be bytes or buffer, not str',) 

更新2

这里最后的代码,“工程”(和不弹出错误TypeError('must be bytes or buffer, not str',)

upload = request.files.get('upload') 
raw = upload.file.read().encode() 
filename = upload.filename 
with open(filename, 'wb') as f: 
    f.write(raw) 

不幸的是,结果是一样的:每一个.txt文件工作正常,但其他文件,如.jpg.pdf ...损坏

我也注意到,这些文件(已损坏的一个)具有比原单(前上传)尺寸较大

这个二进制的东西必须是与Python 3倍

注意的问题:

  • 我使用Python 3.1.3

  • 我用BottlePy 0.11。6(raw bottle.py file,在其上或任何没有2to3的)

+0

没有''.save()'文件对象的方法吗? – thkang 2013-03-17 11:49:27

+0

是的,它是在开发文档,我试过但得到了一个错误'AttributeError('保存',)'(我得到版本0.11.6) – Koffee 2013-03-17 12:32:16

回答

1

在Python 3倍的所有字符串现在unicode的,所以你需要转换的文件上传代码中使用的read()功能。

read()功能藏汉返回一个unicode字符串,您可以通过encode()功能

使用包含在我的第一个问题的代码转换成适当的字节,并更换线路

raw = upload.file.read() 

raw = upload.file.read().encode('ISO-8859-1') 

就这样;)

延伸阅读:http://python3porting.com/problems.html

1

尝试这种情况:

upload = request.files.get('upload') 

with open(upload.file, "rb") as f1: 
    raw = f1.read() 
    filename = upload.filename 
    with open(filename, 'wb') as f: 
     f.write(raw) 

    return "You uploaded %s (%d bytes)." % (filename, len(raw)) 

更新

尝试value

# Get a cgi.FieldStorage object 
upload = request.files.get('upload') 

# Get the data 
raw = upload.value; 

# Write to file 
filename = upload.filename 
with open(filename, 'wb') as f: 
    f.write(raw) 

return "You uploaded %s (%d bytes)." % (filename, len(raw)) 

更新2

this thread,它似乎做一样的,你正在尝试什么......

# Test if the file was uploaded 
if fileitem.filename: 

    # strip leading path from file name to avoid directory traversal attacks 
    fn = os.path.basename(fileitem.filename) 
    open('files/' + fn, 'wb').write(fileitem.file.read()) 
    message = 'The file "' + fn + '" was uploaded successfully' 

else: 
    message = 'No file was uploaded' 
+0

我试过了,它返回一个错误的第一个开放() TypeError(“无效文件:<_io.TextIOWrapper name = 6 encoding ='utf-8'>”,)'(这个错误是针对每种类型的文件发送的) – Koffee 2013-03-17 12:37:27

+0

@Koffee分享'request'的声明。 – ATOzTOA 2013-03-17 15:57:58

+0

@Koffee更新了我的答案... – ATOzTOA 2013-03-17 16:02:31