将回复另存为文件 [英] Save response as file

查看:84
本文介绍了将回复另存为文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have WebAPI method which returns HttpResponseMessage with .csv file as Content:

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

所以我只有单击功能,它可以调用服务器:

So I have just click function, which make call to server :

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

但是我所拥有的-只是内部数据的响应.我试图使用

But all that I've got - is a response with data inside. I've tried to get it as file using this and this answer, but this doesn't change anything.

最好,对该服务器的调用具有 GET 方法btw

Preferably, that call to the server has GET method, btw

推荐答案

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

Is your GenerateReport function returning a promise? Try this:

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

然后,使用诺言下载文件:

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

这篇关于将回复另存为文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆