以前我从 ASP.net core 2.0 发送文件作为 Byte array
,在 Angular 4 应用程序中我调用下面的函数来下载文件
function (response) { // Here response is byte array
var url= window.URL.createObjectURL(res);
var link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", this.zipLocation + ".zip");
link.style.display = "none";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
但是现在我想像下面这样从服务器发送文件路径
https://websiteaddress/file/path/to/download.ext
所以在 Angular 5 中,我可以直接将链接附加到 anchor 标记的 href
属性,然后自动点击它。所以我不需要Convert byte array to url
这里的问题是我不知道如何使用 ASP.net core 创建可下载文件路径并将其发送到前端
而且我还想知道,哪种方法更好,是发送字节数组
还是发送直接链接
?这两者有任何性能问题吗?
最佳答案
If you are using api response as file data
在请求头中添加responseType: 'arraybuffer'
尝试这样的事情:
HTML:
<a (click)="downLoad()">Click To Download</a>
TS:
downLoad(){
this.fileService.getFileFromServer(fileId.toString()).subscribe(respData => {
this.downLoadFile(respData, this.type);
}, error => {
});
}
/**
* Method is use to download file.
* @param data - Array Buffer data
* @param type - type of the document.
*/
downLoadFile(data: any, type: string) {
var blob = new Blob([data], { type: type.toString() });
var url = window.URL.createObjectURL(blob);
var pwa = window.open(url);
if (!pwa || pwa.closed || typeof pwa.closed == 'undefined') {
console.log('Please disable your Pop-up blocker and try again');
}
}
文件服务.ts:
getFileFromServer(id){
return this.http.get(url, {responseType: 'arraybuffer',headers:headers});
}
关于c# - 如何为要在 ASP.net Core 中下载的文件创建可下载文件链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51721397/