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 スクリプトには、フィールド storagefs = 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 に答える