簡體   English   中英

使用 Ajax 和 ashx 上傳文件在 IE 中不起作用

[英]File upload using Ajax and ashx not working in IE

我正在使用 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")消息,但文件沒有被上傳。 預先感謝您的幫助。

而不是使用

string fileName = file.FileName;

使用

Path.GetFileName(file.FileName)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM