Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีทำ File Upload ด้วย Python CGI Programming

เพื่อ Upload ไฟล์ HTML Form ต้องมี Attribute enctype ตั้งเป็น multipart/form-data Input Tag ที่มี File Type จะสร้างปุ่ม "Browse"

ตัวอย่าง

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

Output

ผลลัพธ์ของโค้ดข้างต้นคือ Form ดังนี้ -

File: Choose file Upload

Script save_file.py ด้านล่างจัดการ File Upload -

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

<html>
<body>
  <p>%s</p>
</body>
</html>
""" % (message,)

หากรัน Script บน Unix/Linux ต้องแก้ File Separator ดังนี้ มิฉะนั้นบน Windows คำสั่ง open() ข้างต้นควรทำงานได้ปกติ

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