Handling File Uploads via CGI Forms

Follow the below-specified steps to handle the file uploads via from in CGI script on a Windows Machine using XAMPP Web Server.

Step 1: Firstly, we need to navigate to the htdocs directory in the XAMPP Folder. This directory can be found at “C:\xampp\htdocs“. This directory contains the web pages that we need to run on the XAMPP Server. The standard path is specified, but if you have configured the XAMPP on a different directory, then you need to navigate to that directory.

Step 2: After navigating to the directory, we need to create a basic HTML form that contains file upload functionality which will allow the users to upload the files from the local drive.

Step 3: After creating the file, paste the below code in the file which has the input elements developed using the HTML tags.

HTML




<!DOCTYPE html>
<html>
<head>
    <title>File Upload Form</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f2f2f2;
        }
 
        form {
            width: 400px;
            margin: 0 auto;
            padding: 20px;
            background-color: #fff;
            border: 1px solid #ccc;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
        }
 
        h1 {
            color: green;
        }
 
        h3 {
            color: #333;
        }
 
        input[type="file"] {
            margin: 10px 0;
        }
 
        input[type="submit"] {
            background-color: #007bff;
            color: #fff;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
        }
 
        input[type="submit"]:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
    <form action="/cgi-bin/upload_handler.cgi" method="post" enctype="multipart/form-data" accept-charset="UTF-8">
        <h1>w3wiki</h1>
        <h3>Uploading File Form</h3>
        <input type="file" name="file">
        <input type="submit" value="Upload File">
    </form>
</body>
</html>


Step 4: Now, we will be navigating to the CGI directory which is in the “C:\xampp\cgi-bin” on the XAMP folder. The directory can be different if you have configured the XAMPP server on a different location. But the provided path is the standard and default path.

Step 5: After navigating to the cgi-bin folder. We need to create a new file as upload_handler.cgi. The filename can be anything as per our need. Here, for this example will name the file as upload_handler.cgi.

Step 6: Once the file is been created, we need to paste the below code in the created upload_handler.cgi file. Make sure to replace the shebang as per your Python Executable Path.

Python3




#!C:/Users/Gaurav/AppData/Local/Programs/Python/Python310/python.exe
import cgi
import cgitb
import os
import datetime
cgitb.enable()
form = cgi.FieldStorage()
print("Content-type: text/html\n")
print("<html>")
print("<head>")
print("<title>File Upload Result</title>")
print('<style>')
print('    body { font-family: Arial, sans-serif; background-color: #f2f2f2; }')
print('    .result { width: 500px; margin: 0 auto; padding: 20px; \
                background-color: #fff; border: 1px solid #ccc; border-radius: 5px; \
                box-shadow: 0 0 10px rgba(0, 0, 0, 0.2); }')
print('    .error { color: red; }')
print('    h1 { color: green; }')
print('    h3 { color: #333; }')
print('    .file-info { font-size: 16px; margin-top: 10px; }')
print('</style>')
print("</head>")
print("<body>")
if "file" in form:
    file_item = form["file"]
    if file_item.filename:
        file_name = file_item.filename
        file_path = 'uploads/' + file_name
        with open(file_path, 'wb') as file:
            file.write(file_item.file.read())
        print(f"<h1>w3wiki</h1>")
        print("<h3>CGI Script to Receive File from Form</h3>")
        print(f"<h2>File '{file_name}' uploaded successfully.</h2>")
        upload_datetime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        print(f"<div class='file-info'>Uploaded on: {upload_datetime}</div>")
        local_path = os.path.abspath(file_path)
        print("<div class='file-info'>")
        print(f"Instructions to view the uploaded file locally on your drive:")
        print("<ul>")
        print("<li>Locate the uploaded file in the 'cgi-bin/uploads' folder.</li>")
        print("<li>Open the file using your preferred local application \
        (e.g., a text editor, image viewer, etc.).</li>")
        print("</ul>")
        print("</div>")
    else:
        print("<h1 class='error'>Error: No file was uploaded.</h1>")
else:
    print("<h1 class='error'>Error: No file field found in the form.</h1>")
print("</body>")
print("</html>")


Step 7: In the same cgi-bin directory, we need to create a folder named uploads, which will save all the uploaded files from the form.

Handling File Uploads via CGI

In this article, we will explore how we can handle file uploads via CGI (Common Gateway Interface) script on Windows machines. We will develop a form in which there will be the functionality of uploading the file, when the user uploads the file and submits the form, the data is been passed to the CGI script and the file that is uploaded will get stored in the directory where CGI script is been saved.

Concepts Related

  • CGI Script: A CGI script is nothing but a program that is executed on the web server and can also generate dynamic web content. We can use this to make the web application form, server-side content, etc.
  • Web Server: A web Server is an important utility in which the information requests and responses to the request are done properly, To run the CGI scripts, the Web Server is required.
  • HTTP: Hypertext Transfer Protocol is the foundation of data communication on the World Wide Web. It defines how messages are formatted and transmitted.

Prerequisites

Similar Reads

Handling File Uploads via CGI Forms

Follow the below-specified steps to handle the file uploads via from in CGI script on a Windows Machine using XAMPP Web Server....

Running and Testing the CGI Script

...

Contact Us