使用API​​无法下载文件

时间:2016-03-16 13:32:01

标签: javascript api

我对我的下载方法的API调用存在问题。

以下是我使用的JS代码,它与淘汰赛一起使用:

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

这是我的API解决方案:

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

file参数包含文件路径和名称。

谁能告诉我我做错了什么?

响应始终正常,但它在错误分支上,文件未打开。文件是PDF,Excel,Word。

1 个答案:

答案 0 :(得分:0)

编辑2:

你可以使用target =&#34; _blank&#34;而不是下载以在新标签页中打开pdf。

修改&#39; a&#39; tag:

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

编辑: 这也可以帮到你 link

一种解决方案是编码到base64并使用它:

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

然后将响应数据放入href

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

我不知道如何在你的API中处理它。