我正在尝试通过单击按钮来下载文件,但不是将我的文件作为“myFile.csv”获取,而是返回的文件称为“download”而没有任何扩展名。我也尝试了以下解决方案Download text/csv content as files from server in Angular
这是服务器响应
var result = engine.WriteString(recs);
response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(Encoding.UTF8.GetBytes(result)) };
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = String.Format("TVF_Export_{0}.csv", DateTime.Now.ToShortDateString())
};
return response;
客户端代码
$http.post(url, filters).success(function (data, status, headers, config) {
console.log(data);
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:attachment/csv,' + encodeURI(data);
hiddenElement.target = '_blank';
hiddenElement.download = 'myFile.csv';
hiddenElement.click();
}).error(function (data, status, headers, config) {
console.log('[DEBUG] error ' + data);
});
答案 0 :(得分:0)
如果您可以控制服务器响应,则可以确保在响应中设置了以下标头:
Content-Disposition: attachment; filename=myFile.csv;
您还应指定Content-Type: text/csv
或此:
Content-Type: application/force-download