我已经使用下面的代码异步上传文件到服务器:
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标记中。
无论如何都要在客户端得到结果(“DONE”或“FAILED”)吗?
function uploadFinished()
{
if ( response == "DONE" )
{
// show the result
}
else
{
// show error
}
}
请不要在不使用JQuery的情况下帮助我。
提前致谢。
答案 0 :(得分:2)
您可以使用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;
}