如何使用 Python CGI 程式設計執行檔案上傳?


要上傳檔案,HTML 表單必須有一個將 enctype 屬性設定為 multipart/form-data。具有檔案型別的 input 標記建立一個“瀏覽”按鈕。

示例

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

輸出

此程式碼的結果是以下表單 −

File: Choose file
Upload

以下是處理檔案上傳的 save_file.py 指令碼 −

#!/usr/bin/python
import cgi, os
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
# Get filename here.
fileitem = form['filename']
# 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('/tmp/' + 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,)

如果你在 Unix/Linux 上執行上述指令碼,則你需要注意如下替換檔案分隔符,否則在你 windows 計算機上的上述 open() 語句應該可以正常工作。

fn = os.path.basename(fileitem.filename.replace("", "/" ))

更新於:09-9-2023

3K+ 瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.