gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:10:25 24 4
gpt4 key购买 nike

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

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

关于javascript - 在我的 Python CGI 脚本中,如何将通过用户在表单中输入的数据的 POST 请求上传的文件保存到磁盘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15947988/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com