1

I have an issue with my API call to my download method.

Here is the JS code I'm using, it's used with knockout:

self.downloadFile = function(file) {
    // Ajax Call Get All Leave Records
    $.ajax({
        type: "POST",
        url: "/api/v1/CompanyFilesApi/DownloadFile",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: ko.toJSON(file),
        success: function (data) {
            console.log("Here is your file");
        },
        error: function (error) {

            alert(error.status + " <--and--> " + error.statusText);
        }
    });
    // Ends Here
};

And here is my API solution:

public HttpResponseMessage DownloadFile(FileModel file)
    {
        var path = file.FilePath;
        var result = Request.CreateResponse(HttpStatusCode.OK, file.FileName);
        var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
        result.Content = new StreamContent(stream);
        result.Content.Headers.ContentType =
            new MediaTypeHeaderValue("application/octet-stream");
        return result;
    }

The file parameter contains the file path and name.

Can anyone tell me what I'm doing wrong?

The response is always ok but it goes on the error branch and the file is not open. The files are PDF, Excel, Word.

Michael
  • 2,631
  • 2
  • 24
  • 40
Vlad
  • 21
  • 1
  • 2
  • 7

1 Answers1

0

EDIT 2:

You can use target="_blank" instead of download to open the pdf in a new tab.

To modifify the 'a' tag :

$("#your-a-tag-id").attr("href", "data:application/octet-stream;base64," + fileDataString);

EDIT: This could also help you link


One solution would be to encode to base64 and use it as such :

...
dataType: "application/octet-stream;base64"
...

then put the response data in a href

<a href="data:application/octet-stream;base64,/*YOUR FILE DATA*/" download="your filename">

I'm not sure how to deal with that in your API though.

Community
  • 1
  • 1
phenxd
  • 689
  • 4
  • 17
  • I don't know if this is even possible to put the data in a markup after the response. Is it? And another think, i don't use the html5 markup 'download' because it it's not supported by older browsers, e.g. IE8 – Vlad Mar 17 '16 at 06:13
  • I will try you new answer and come back with more details. Tnx – Vlad Mar 18 '16 at 06:23