简体   繁体   中英

Download file using API not working

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM