在我的Python CGI脚本中,我如何将用户在表单中输入的数据通过POST请求上传的文件保存到磁盘

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?

本文关键字:POST 数据 请求 磁盘 保存 文件 表单 脚本 CGI Python 我的      更新时间:2023-09-26

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

<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脚本中,我有字段存储fs = cgi.FieldStorage(),我知道如何获得文本值,即fs['key'].value

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

我希望我说得够清楚了。谢谢!

使用以下代码将文件存储到磁盘

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'