gpt4 book ai didi

javascript - 使用通用处理程序异步上传文件

转载 作者:行者123 更新时间:2023-12-02 17:09:06 25 4
gpt4 key购买 nike

我使用下面的代码将文件异步上传到服务器:

HTML:

<form id="file_upload" action="UploadFile.ashx" target="upload-target" method="post" enctype="multipart/form-data" onsubmit="javascript:return uploadClicked();">
<input type="file" id="newFile" name="newFile" />
<input type="submit" />
<iframe id="upload-target" name="upload-target"></iframe>
</form>

点击提交按钮后,uploadClicked()函数将被触发:

function uploadClicked() {
if (condition == true)
return true; // the form will submit
else
return false;
}

现在通用处理程序UploadFile.ashx将保存文件并返回结果:

if (context.Request.Files.Count > 0)
{
context.Request.Files["newFile"].SaveAs(HttpContext.Current.Server.MapPath("/Images/myFile.png"));
response.Write("DONE");
}
else
{
response.Write("FAILED");
}

效果很好,结果将显示在 iframe 标记中。

有没有办法像这样在客户端获得结果(“完成”或“失败”)?

function uploadFinished()
{
if ( response == "DONE" )
{
// show the result
}
else
{
// show error
}
}

请帮助我在不使用 JQuery 的情况下完成此操作。

提前致谢。

最佳答案

您可以使用XHR2 FormData对象将文件异步上传到服务器并从服务器处理程序检索响应:

function uploadClicked() {
var fd = new FormData();
var file = document.getElementById('newFile');
fd.append(file.name, file.files[0]);

var xhr = new XMLHttpRequest();
var form = document.getElementById('file_upload');
xhr.open(form.method, form.action);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// xhr.responseText will contain the response from the server
alert(xhr.responseText);
}
};
xhr.send(fd);

// We are submitting the form asynchronously
return false;
}

关于javascript - 使用通用处理程序异步上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24973337/

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