1

客户端有一个简单的表单,它接受一个文本和一个文件:

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

使用 Javascript,我将数据发送到服务器的 Python CGI 脚本:

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

    }

在服务器端 Python CGI 脚本中,我有字段 storage fs = cgi.FieldStorage(),并且我知道如何获取文本值,即fs['key'].value.

如何保存上传到磁盘的文件?

我希望我足够清楚。谢谢!

4

1 回答 1

7

使用此代码将文件存储在磁盘上

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'
于 2013-04-11T12:02:31.427 回答