Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách upload file sử dụng Python CGI Programming?

Để upload file, HTML form phải có thuộc tính enctype="multipart/form-data". Thẻ input type file tạo nút "Browse".

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>

Script save_file.py xử lý upload:

#!/usr/bin/python
import cgi, os
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
fileitem = form['filename']
if fileitem.filename:
    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
<html>
<body>
  <p>%s</p>
</body>
</html>
""" % (message,)

Trên Unix/Linux, cần thay file separator: fn = os.path.basename(fileitem.filename.replace("\\", "/")).