1

使用 BottlePy,我使用以下代码上传文件并将其写入磁盘:

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:

它返回以下错误:

TypeError('必须是字节或缓冲区,而不是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 3x 的问题

笔记 :

4

2 回答 2

2

在 Python 3x 中,所有字符串现在都是 unicode,因此您需要转换read()此文件上传代码中使用的函数。

read()函数还返回一个 unicode 字符串,您可以通过encode()函数将其转换为正确的字节

使用我的第一个问题中包含的代码,并替换该行

raw = upload.file.read()

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

就这样 ;)

进一步阅读: http: //python3porting.com/problems.html

于 2013-03-19T08:39:32.750 回答
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

看到这个线程,它似乎和你正在尝试的一样......

# 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'
于 2013-03-17T11:37:55.563 回答