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?

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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


            });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.