【问题标题】: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?在我的 Python CGI 脚本中,如何将通过用户在表单中输入的数据的 POST 请求上传的文件保存到磁盘?
【发布时间】:2013-04-12 01:49:29
【问题描述】:

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

<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

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

我希望我已经足够清楚了。谢谢!

【问题讨论】:

    标签: javascript python html cgi


    【解决方案1】:

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

    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'
    

    【讨论】:

    • 太棒了!非常感谢。只是对阅读本文的人的补充,还必须导入 os.path 和 cgi。
    猜你喜欢
    • 2020-03-20
    • 2014-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多