2013-03-17 82 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