2012-06-03 40 views
1

我真的搜索了大約50個相關頁面,但從未見過類似於我的問題的問題。當我按提交按鈕時,它會調用腳本,但腳本返回一個空白頁面,並且我看不到任何文件已上傳。在我的代碼中沒有輸入錯誤,我檢查了好幾次,我真的需要爲我的項目運行此代碼。可能是什麼問題?我在ubuntu下運行的Apache和我的代碼是:Python/CGI - 上傳文件嘗試返回空白頁面

的html代碼:

<html><body> 
<form enctype="multipart/form-data" action="save_file.py" method="post"> 
<p>File: <input type="file" name="file"></p> 
<p><input type="submit" value="Upload"></p> 
</form> 
</body></html> 

Python代碼:

#!/usr/bin/env python 
import cgi, os 
import cgitb; cgitb.enable() 

try: #windows needs stdio set for binary mode 
    import msvcrt 
    msvcrt.setmode (0, os.O_BINARY) 
    msvcrt.setmode (1, os.O_BINARY) 
except ImportError: 
    pass 

form = cgi.FieldStorage() 

#nested FieldStorage instance holds the file 
fileitem = form['file'] 

#if file is uploaded 
if fileitem.filename: 
    #strip leading path from filename to avoid directory based 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' 

print """\ 
Content-Type: text/html\n 
<html><body> 
<p>%s</p> 
</body></html> 
""" % (message,) 
+0

錯誤日誌說...? –

+0

我不知道在python cgi中尋找錯誤日誌的位置,你能幫我嗎? – user1433743

+0

無論你的Web服務器放在哪裏。 –

回答

1

我只是測試你的腳本,有一些小的修正的路徑讓它在本地爲我工作。通過正確設置路徑並正確設置權限,此代碼可以正常工作。

以下是確保的事情:

  1. 在HTML文件中的表單屬性,請確保您都指向Python腳本,住在一個cgi-bin目錄:action="/cgi-bin/save_file.py"。對我來說,我在我的web服務器的根目錄下有一個cgi-bin,並且在那裏放置了python腳本。如果你是從一個標準的文件位置在Web服務器上運行該腳本將無法正常工作

  2. 確保您save_file.py具有可執行權限:chmod 755 save_file.py

  3. 在你save_file.py,確保您構建一個有效的路徑來打開文件進行保存。我做了我的只是爲了測試目的絕對的,但這樣的事情:open(os.path.join('/path/to/upload/files', fn)

有了正確設置這些點,你不應該有任何問題。

+0

那麼這裏是我的配置: 我的腳本文件都在「/ var/www/python/cgi-bin」下,我將chmod -R 755應用到「/ var/www/python」文件夾。 最後文件的文件夾路徑是「/ var/www/python/cgi-bin/files」,我爲save_file設置了chmod 755權限。什麼可能是這個問題?我的路線是否有正確的腳本? – user1433743

+0

@ user1433743:通常情況下,您不會將html用於cgi-bin位置。這隻會是CGI腳本,你會從你的標準文檔位置引導你的URL。但我不認爲你的問題。 '/ files',但可能是錯誤的。這是本地服務器到/ files(而不是url路徑)的絕對路徑,它不是「/ var/www/python/cgi-bin/files」。嘗試設置絕對路徑。 – jdi

+0

我will.try檢查錯誤日誌。因爲我做了你所說的一切,我仍然得到空白頁面,沒有上傳。 – user1433743