我正在使用ajax和ashx文件上传文件,除了在Internet Explorer(IE11)中,它在其他浏览器中运行良好,我也在网上搜索并尝试了不同的建议,但仍然失败了。
这是我的ajax代码:
function uploadFile() {
var formData = new FormData();
formData.append('file', $('#fileupload')[0].files[0]);
$.ajax({
type: 'post',
url: 'fileUploader.ashx',
data: formData,
success: alert("Success!"),
processData: false,
cache: false,
contentType: false,
error: function () {
alert("Something went wrong!");
}
});
}
这是我的ashx代码:
public class fileUploader : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
try
{
string dirFullPath = HttpContext.Current.Server.MapPath("~/Attachment_/");
string[] files;
files = System.IO.Directory.GetFiles(dirFullPath);
string str_file = "";
foreach (string s in context.Request.Files)
{
HttpPostedFile file = context.Request.Files[s];
string fileName = file.FileName;
string fileExtension = file.ContentType;
if (!string.IsNullOrEmpty(fileName))
{
//save to path
fileExtension = Path.GetExtension(fileName);
str_file = "Attachment_" +fileName;
string pathToSave = HttpContext.Current.Server.MapPath("~/Attachment_/") + str_file;
file.SaveAs(pathToSave);
}
}
context.Response.Write(str_file);
}
catch (Exception)
{
throw;
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
我哪里出错了?我在其他浏览器上试过并测试了这个特别是chrome并且上面的代码正在运行,但它在IE上失败了。它也不会抛出任何错误,并显示alert("Success")
消息,但文件未被上传。在此先感谢您的帮助。
答案 0 :(得分:0)
代替使用
string fileName = file.FileName;
使用
Path.GetFileName(file.FileName)