Sam Jones
Sam Jones

Reputation: 4618

c# asp.net MVC Download a file via Ajax

I'm pretty sure this isn't possible but I thought I'd ask...

I have a FileResult which returns a file, when it works there's no problem. When there's an error in the FileResult for some reason, I'd like to display an exception error message on the users screen, preferably in a popup.

Can I do an Ajax post which returns a file when successful and displays a message if not?

Upvotes: 1

Views: 3256

Answers (3)

Muhammad Hammad Ahmad
Muhammad Hammad Ahmad

Reputation: 89

Controller (MyApiController) Code:

public ActionResult DownloadFile(String FileUniqueName)
    {
        var rootPath = Server.MapPath("~/UploadedFiles");
        var fileFullPath = System.IO.Path.Combine(rootPath,FileUniqueName);
        byte[] fileBytes = System.IO.File.ReadAllBytes(fileFullPath);
        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, "MyDownloadFile");

    }

Jquery Code:

$(document).on("click"," a ", function(){ //on click of anchor tag

                var funame=$(this).attr('uname'); /*anchor tag attribute "uname" contain file unique name*/
                var url = "http://localhost:14211/MyApi/DownloadFile?FileUniqueName= " + funame;
                window.open(url);


            });

Upvotes: 0

haim770
haim770

Reputation: 49123

Not specifically related to MVC but...

it can be done using XMLHttpRequest in conjunction with the new HTML5 File System API that allows you to deal with binary data (fetched from http response in your case) and save it to the local file system.

See example here: http://www.html5rocks.com/en/tutorials/file/xhr2/#toc-example-savingimages

Upvotes: 0

Murtuza Kabul
Murtuza Kabul

Reputation: 6524

I think it is not possible cause in order to handle ajax post, you will have to write a javascript handler on the client side and javascript cannot do file IO on client side.

However, what you can do is, make an ajax request to check if file exists and can be downloaded. If, not, respond to that request negatively which will popup a dialog on client side. If successful, make a file download request.

Upvotes: 3

Related Questions