从Angular JS中的Web API下载csv文件

我的API控制器返回的是csv文件,如下所示:

    [HttpPost]

public HttpResponseMessage GenerateCSV(FieldParameters fieldParams)

{

var output = new byte[] { };

if (fieldParams!= null)

{

using (var stream = new MemoryStream())

{

this.SerializeSetting(fieldParams, stream);

stream.Flush();

output = stream.ToArray();

}

}

var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(output) };

result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")

{

FileName = "File.csv"

};

return result;

}

我的angularjs将发送和接收csv文件如下所示:

$scope.save = function () {

var csvInput= extractDetails();

// File is an angular resource. We call its save method here which

// accesses the api above which should return the content of csv

File.save(csvInput, function (content) {

var dataUrl = 'data:text/csv;utf-8,' + encodeURI(content);

var hiddenElement = document.createElement('a');

hiddenElement.setAttribute('href', dataUrl);

hiddenElement.click();

});

};

在chrome中,它将下载一个名为,document但没有文件扩展名的文件。该文件的内容为[Object object]

在IE10中,没有下载任何内容。

我该怎么做才能解决此问题?

回答:

像这样尝试:

File.save(csvInput, function (content) {

var hiddenElement = document.createElement('a');

hiddenElement.href = 'data:attachment/csv,' + encodeURI(content);

hiddenElement.target = '_blank';

hiddenElement.download = 'myFile.csv';

hiddenElement.click();

});

以上是 从Angular JS中的Web API下载csv文件 的全部内容, 来源链接: utcz.com/qa/408127.html

回到顶部