Computer >> Máy Tính >  >> Lập trình >> Python

Làm cách nào để tải tệp lên bằng Lập trình Python CGI?


Để tải tệp lên, biểu mẫu HTML phải có thuộc tính enctype được đặt thành multiart / form-data. Thẻ đầu vào có loại tệp sẽ tạo nút "Duyệt qua".

Ví dụ

<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>

Đầu ra

Kết quả của mã này là dạng sau -

File: Choose file
Upload

Đây là tập lệnh save_file.py để xử lý tải lên tệp -

#!/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,)

Nếu bạn chạy tập lệnh trên trên Unix / Linux, thì bạn cần chú ý thay thế dấu phân tách tệp như sau, nếu không trên máy windows của bạn ở trên câu lệnh open () sẽ hoạt động tốt.

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