Javascript 使用通用处理程序异步上载文件
我已经使用下面的代码将文件异步上传到服务器: HTML:Javascript 使用通用处理程序异步上载文件,javascript,asp.net,ajax,ashx,generic-handler,Javascript,Asp.net,Ajax,Ashx,Generic Handler,我已经使用下面的代码将文件异步上传到服务器: 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"
<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>
现在,通用处理程序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的情况下执行此操作。
提前感谢。您可以使用该对象将文件异步上载到服务器,并从服务器处理程序检索响应:
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;
}
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;
}