0

I have an hyperlink of the file name and want to download the file retrieved from database. I can download the file, but the form is posted during this process. Instead of this, I want the form is not posted with the help of ajax, but my code hits error in Ajax call. Is there a smart way to achieve this?

View:

<a onclick="downloadFile(@Model.ID);" target="blank">@Model.FileName</a>


<script>
function downloadFile(id) {

    $.ajax({
        url: '@Url.Action("Download", "Controller")',

        type: "POST",
        data: JSON.stringify({ 'id': id }),
        dataType: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            if (data.status == "Success") {
                alert("Done");
            } else {
                alert("error occurs on the database level!");
            }
        },
        error : function () {
            alert("an error has occured!!!");
        }
    });
}
</script>


Controller:

public FileContentResult Download(int id)
{
    var dataContext = repository.Attachments.FirstOrDefault(p => p.ID == id);
    if (dataContext != null)
    {
        return File(dataContext.FileData, dataContext.FileMimeType);
    }
    else
    {
        return null;
    }
}
4
  • What is the error..? Commented Jul 10, 2015 at 14:47
  • @Sippy "an error has occured!!!" in alert window. Commented Jul 10, 2015 at 14:56
  • Yeah that's not helping anyone. What does it say in the console? Commented Jul 10, 2015 at 15:00
  • Sorry :( There is no error on the console and only a post address: localhost:3501/Controller/Download/86. The action method is called properly and returns file result. But it cannot be rendered or Save dialog is not opened. Commented Jul 10, 2015 at 15:04

2 Answers 2

1

why not just change your link to

<a href="@Url.Action("Download", "Controller", new { id = Model.ID })" >@Model.FileName</a>
Sign up to request clarification or add additional context in comments.

6 Comments

As I said in the question, "... I can download the file, but the form is posted during this process. Instead of this, I want the form is not posted with the help of ajax". So, I just want to open the image or file by clicking the hyperlink. Is it possible?
sounds like you want exactly what i posted above. if you click the link and the file exists you should get a file save dialog or something from browser
Thanks a lot for your help. Yes, you are right. But the problem is related to image files. If I can manage to open them in a popup window of jquery image addons (i.e. fancybox) the problem will be solved completely. Do you have any idea for the rest of the problem (images)?
that's a whole nother ball of wax. you can convert your FileData to a base64 string for something like that. you probably want to search display image from byte array to get some answers on different ways to handle images
this page has a method at the bottom that i haven't tried but may work for you binaryintellect.net/articles/… you can try it by just adding and <img> to your like this <img src='@Url.Action("Download", "Controller", new { id = Model.ID })'/>
|
1

The easiest way to download a file is to link it directly like calling the action: "/FileController/Download?Id=2"

The problem is that if you get an error, it will redirect you to a blank page...

To resolve this i created this function:

function DownloadFile(id, Type) {
    var hiddenIFrameID = 'hiddenDownloader',
        iframe = document.getElementById(hiddenIFrameID);

    if (iframe === null) {
        iframe = document.createElement('iframe');
        iframe.id = hiddenIFrameID;
        iframe.style.display = 'none';
        document.body.appendChild(iframe);
    }

    if (Type == undefined || Type == "")
        Type = null;

    iframe.src = "/File/Download?ID=" + id;
}

This function creates an hidden iframe pointing to the file path (action). If it gives an error, it will not blow up your page.

5 Comments

Thanks for reply. But id did not make any sense and still the same behaviour: If the file is pdf, excel, etc. a Save Dialog appears. If it is an image file, nothing is opened. So, I need to open a window when clicking a link of an image. It would be also better to open a popup window and display images in it i.e. using fancybox.
That's strange... In my application i can download any file through this
In that case it is better that you post all the necessary methods in Controller and View (also div if that is used to display image). On the other hand, do you meant that you open Save Dialog for every types of file? Or you open popup dialog for images and display them in it?
I solved the problem regarding to the image files as indicated on this page. So, thanks a lot for your help. Voted+
I already selected @Sky Fang's answer :) The only reason to post the latest code it to help for those who face with the same problem. Thanks again.

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.