从角JS网页API下载csv文件 [英] download csv file from web api in angular js
问题描述
下面看到我的API控制器返回一个CSV文件:
my API controller is returning a csv file as seen below:
[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文件如下:
and my angularjs that will send and receive the csv file is shown below:
$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();
});
};
在镀铬,它下载一个被称为文件
,但没有文件类型的扩展名的文件。
该文件的内容是 [Object对象]
。
In chrome, it downloads a file which is called document
but has no file type extension.
The content of the file is [Object object]
.
在IE10中,没有什么是下载。
In IE10, nothing is downloaded.
我可以做些什么来解决这个问题?
What could i do to fix this?
更新:
这可能会为你们同样的问题制定出有:<一href=\"http://stackoverflow.com/questions/20303988/generate-csv-from-mvc-web-api-htt$p$psponse-and-receive-it-by-angularjs-for-downl/20917641#20917641\">link
推荐答案
试一试这样的:
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();
});
根据<一个最优秀的答案
href=\"http://stackoverflow.com/questions/17836273/export-javascript-data-to-csv-file-without-server-interaction\">this问题
这篇关于从角JS网页API下载csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!