javascript - 将响应另存为文件

标签 javascript angularjs asp.net-web-api download httpresponse

我有 WebAPI 方法,它返回 HttpResponseMessage.csv 文件作为内容:

private static HttpResponseMessage FileAsAttachment(string file)
{
    var now = DateTime.Now;
    var result = new HttpResponseMessage(HttpStatusCode.OK);

    result.Content = new StringContent(file);
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); //attachment will force download
    result.Content.Headers.ContentDisposition.FileName = string.Format("Report-{0}.csv", now.ToString("MMMM"));

    return result;
}

所以我只需点击功能,即可调用服务器:

$scope.GenerateReport = function() {
     var endDate = '2016-04-30';
     UserDaysSummary.generateReport({endDate: endDate }, function (result) {
          console.log("Export");
     });
}

但我所得到的只是一个内含数据的响应。 我尝试使用 this 将其作为文件获取和 this回答,但这并没有改变任何东西。

最好,对服务器的调用有 GET 方法,顺便说一句

最佳答案

您的 GenerateReport 函数是否返回 promise ?试试这个:

userDaysSummary.generateReport = function(endDate) {
    var defer = $q.defer();

    $http.get('path/to/api', { endDate: endDate }, { responseType: 'arrayBuffer' }).then(function(data, status, headers, config) {
        var results = {
            data: data, //your file is here
            headers: headers(), //headers are here
            status: status,
            config: config
        };

        //return a success promise containing the response object
        defer.resolve(results);

    }, function(data, status, headers, config) {
        defer.reject(data);
    });

    return defer.promise;
}

然后,使用 promise 下载文件:

userDaysSummary.generateReport(endDate).then(function(response) {
    //get the file
    var octetStreamMime = 'application/octet-stream';

    //get the headers' content disposition
    var cd = response.headers["content-disposition"];

    //get the file name with regex
    var regex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
    var match = regex.exec(cd);

    //is there a fiel name?
    var fileName = match[1] || "myDefaultFileName.csv";

    //replace leading and trailing slashes that C# added to your file name
    fileName = fileName.replace(/\"/g, "");

    //determine the content type from the header or default to octect stream
    var contentType = response.headers["content-type"] || octetStreamMime;

    //finally, download it
    try {
        var blob = new Blob([response.data], {type: contentType});

        //downloading the file depends on the browser
        //IE handles it differently than chrome/webkit
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveOrOpenBlob(blob, fileName);
        } else {
            var objectUrl = URL.createObjectURL(blob);
            window.open(objectUrl);
        }
    } catch (exc) {
        console.log("Save Blob method failed with the following exception.");
        console.log(exc);
    }

}, function(error) {
    //an error occurred while trying the API, handle this
});

关于javascript - 将响应另存为文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36893433/

相关文章:

angularjs:$timeout 用法(服务内部)

angularjs - 使用 Chutzpah + AngularJS + jasmine 测试指令

asp.net - 何时使用Request.RegisterForDispose?

javascript - Dropzone - Uncaught Error : No URL provided

JavaScript - 我应该在抛出异常的 "else"之后写 "if"吗?

javascript - AngularJS 创建下拉菜单

c# - WebAPI 自托管 : Can't bind multiple parameters to the request's content

javascript - 如何从 Google Sheet 下载具有特定边距和分页符的 PDF 文件?

javascript - 正则表达式 - 避免表达式中出现字符串

c# - 如何在Web API中上传 "text/plain"字符串