【问题标题】:File upload using Ajax and ashx not working in IE使用 Ajax 和 ashx 上传文件在 IE 中不起作用
【发布时间】:2017-03-08 00:52:13
【问题描述】:

我正在使用 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") 消息,但文件没有被上传。提前感谢您的帮助。

【问题讨论】:

  • FormData 未定义请参考这个-stackoverflow.com/questions/26206105/…
  • 我已经看过了,它也对我不起作用 :( 我试过这个 但在 IE 中仍然失败。
  • 使用 AjaxForm 而不是 FormData
  • 嗨@viveknuna 你有样品吗?抱歉,我是 ajaxForm 新手。我将如何转换?谢谢!
  • 我正在使用jQuery File Upload 上传文件并使用通用处理程序处理(在我的情况下:保存)它们。对我来说效果很好。你有考虑过使用这个 jQuery 插件吗?

标签: c# ajax internet-explorer file-upload ashx


【解决方案1】:

而不是使用

string fileName = file.FileName;

使用

Path.GetFileName(file.FileName)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 1970-01-01
    • 2011-09-14
    • 2015-12-04
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    相关资源
    最近更新 更多