简体   繁体   中英

File upload using Ajax and ashx not working in IE

I'm uploading a file using ajax and ashx file and it works well in other browser except in Internet Explorer (IE11), I had also search the web and tried different suggestions but still failed.

Here is my ajax code:

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!");
            }
        });
}

Here is my ashx code:

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;
        }
    }
}

Where did I go wrong? I tried and tested this on other browser specially chrome and the above codes are working, but it fails on IE. It also doesn't throw any error, and shows the alert("Success") message, but the file is not being uploaded. Thanks in advance for your help.

Instead of using

string fileName = file.FileName;

use

Path.GetFileName(file.FileName)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM