Skip to content

Instantly share code, notes, and snippets.

@shenweiyan
Last active September 9, 2019 03:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shenweiyan/e118dd847fcb62774b188a40a4e682eb to your computer and use it in GitHub Desktop.
Save shenweiyan/e118dd847fcb62774b188a40a4e682eb to your computer and use it in GitHub Desktop.
File Upload CGI Script written in Python.
#!/bin/bash
mkdir ./cgi-bin/
cp upload.cgi ./cgi-bin/
chmod +x ./cgi-bin/upload.cgi
mkdir ./upload/
python -m CGIHTTPServer 8080
#!/usr/bin/python
# -*- coding: utf-8 -*-
import cgi, cgitb, os, sys
UPLOAD_DIR = './upload'
def save_uploaded_file():
print 'Content-Type: text/html; charset=UTF-8'
print
print '''
<html>
<head>
<title>Upload File</title>
</head>
<body>
'''
form = cgi.FieldStorage()
if not form.has_key('file'):
print '<h1>Not found parameter: file</h1>'
return
form_file = form['file']
if not form_file.file:
print '<h1>Not found parameter: file</h1>'
return
if not form_file.filename:
print '<h1>Not found parameter: file</h1>'
return
uploaded_file_path = os.path.join(UPLOAD_DIR, os.path.basename(form_file.filename))
with file(uploaded_file_path, 'wb') as fout:
while True:
chunk = form_file.file.read(100000)
if not chunk:
break
fout.write (chunk)
print '<h1>Completed file upload</h1>'
print '''
<hr>
<a href="../upload.html">Back to upload page</a>
</body>
</html>
'''
cgitb.enable()
save_uploaded_file()
<html>
<head>
<title>Upload File</title>
</head>
<body>
<h1>Upload File</h1>
<form action="cgi-bin/upload.cgi" method="POST" enctype="multipart/form-data">
File: <input name="file" type="file">
<input name="submit" type="submit">
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment