在我的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?

查看:377
本文介绍了在我的Python CGI脚本中,如何将用户在表单中输入的数据的POST请求保存到磁盘上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

客户端有一个简单的表单,其中包含文本和文件:

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>

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

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

    }

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

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, i.e. 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'

这篇关于在我的Python CGI脚本中,如何将用户在表单中输入的数据的POST请求保存到磁盘上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆