1

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?

tereško
  • 58,060
  • 25
  • 98
  • 150
Sam Jones
  • 4,443
  • 2
  • 40
  • 45
  • 3
    http://stackoverflow.com/questions/6028623/handeling-an-asp-net-mvc-fileresult-returned-in-an-jquery-ajax-call – Andrew Jul 23 '13 at 11:31

3 Answers3

3

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.

Murtuza Kabul
  • 6,438
  • 6
  • 27
  • 34
0

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

haim770
  • 48,394
  • 7
  • 105
  • 133
0

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


            });