2014-01-12 33 views
5

我試圖打開一個gif文件,併發送正確的字節到一個網頁瀏覽器,但它拋出異常「不能將‘字節’對象隱含str的」坦白地說,我百思不得其解,因爲我已經將它轉換爲一個字符串。不能轉換「字節」對象爲str隱含

files=open("WebContent/"+fileName,"rb") 
#size=os.path.getsize("WebContent/"+fileName) 
text=str(files.read()) 
text=text.encode('UTF-8') 
defaultResponseCode="HTTP/1.1 200 OK\r\nContent-Type: image/gif\r\nContent-Transfer-Encoding: binary\r\nContent-Length: 29696\r\n\r\n"+text 

在此先感謝!

+1

'文本= text.encode( 'UTF-8')'現在,它不再是一個字符串... – Doorknob

+0

天上所以我應該只是做 'text.encode(' UTF-8 ')'? – user1564622

+1

爲什麼要轉換爲字符串?你不需要那個。你的Content-Transfer-Encoding頭聲稱是「二進制」的,因此沒有編碼被應用於數據。就像從文件中讀取圖像一樣發送圖像。 –

回答

1

在這裏,您試圖字節(文件,'rb'模式打開)轉換爲字符串:

text = str(files.read()) 

改變上述行來此:

text = files.read().decode(encoding='change_to_source_file_encoding') 

,那麼你可以轉換unicode字符串以UTF- 8字節的字符串與:

text = text.encode('UTF-8') 

如果源編碼是utf-8你可以ju ST通字節串從files.read()到您的結果字符串沒有無謂的解碼/編碼步驟(從UTF-8字節串,並再次爲UTF-8字節)...

更新:嘗試用requests

url = 'url' 
files = {'file': open("WebContent/"+fileName, 'rb')} 
response = requests.post(url, files=files) 

更新2:根據(... Content-Type: image/gif ...你有所需格式的數據的內容類型的響應報頭剛過

files.read()沒有任何編碼/解碼!

+0

它告訴我全球名稱'unicode'沒有定義 – user1564622

+0

@ user1564622現在試試,你正在使用python3嗎? – ndpu

+0

現在它說我有一個無效的字節 – user1564622

0

對於那些主要感興趣的是Popen而不是psql,這裏是一個調試工作python3腳本,基於原Popen問題,並納入提供的建議。

#!/usr/bin/env python3 

# print a list of postgresql databases via psql 
import subprocess 

username = "postgres" 
dbname = "postgres" 

p = subprocess.Popen(
    args = ['psql', '-qAt', '-U', username, '-d', dbname], 
# args = ['psql', '-qAt', '-d', dbname], # with adequate user permissions 
    stdin = subprocess.PIPE, 
    stdout = subprocess.PIPE 
) 
sql = b"SELECT datname FROM pg_database;" 

dbs = p.communicate(b"SELECT datname FROM pg_database;")[0].split(b'\n') 

for db in dbs: 
    print("%s" % db.decode("utf-8")) 

p.wait() 
0

在蟒蛇3+我得到類似的問題,我刪除text.encode("utf-8")和使用text.strip()

text = text.strip() 
相關問題