简体   繁体   中英

In my Python CGI script, how do I save to disk a file uploaded via POST request of data entered by the user in a form?

The client has a simple form that takes a text and a file:

<form name="add_show" id="add_show" action="" method="GET">

    <label class="text-info">Show Name:</label>
    <input type="text" id="show_name" name="show_name" placeholder="My Show Name" required><br><br>

    <label class="text-info">Show's File (JSON):</label>
    <input type="file" id="file" name="file" required><br><br>

    <p><input class="btn btn-danger btn-small" name="button2" value="Add the Show!" onClick="addFullShow(this.form)"></p>

</form>

With Javascript I send the data to the server's Python CGI script:

function addFullShow(form) {

      alert("about to send form");

      var formElement = form;
      formData = new FormData(formElement);

      var xhr = new XMLHttpRequest();
      xhr.open("POST", "myScript.cgi");
      xhr.send(formData);

    }

And in the server side Python CGI script I have the field storage fs = cgi.FieldStorage() , and I know how to get the text values, ie fs['key'].value .

How do I save the file uploaded to disk?

I hope I'm clear enough. Thanks!

use this code to store the file on disk

import os, cgi
fs = cgi.FieldStorage()
fileitem = fs['userfile']

# Test if the file was uploaded
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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM