c# - 如何为要在 ASP.net Core 中下载的文件创建可下载文件链接

标签 c# download .net-core asp.net-core-2.0 asp.net-core-webapi

以前我从 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/

相关文章:

c# - 在 DataGridView 上托管自定义控件,这些控件从 DataTable 填充数据

iPhone 故障保护多个文件下载

php - 使用 PHP 下载大型 "private"文件

c# - 如何删除某些文本中而不是某些文本开头存在的任何 UTF-8 BOM

c# - 根据文本框中键入的值搜索 gridview?

c# - 在列表框内添加一个动态文本框

jquery - 如何获取下载图片的完整路径?

asp.net-core - .NET Core 如何使用不同的环境?

azure - 处理 Durable Functions 中的服务总线消息

c# - 从 ASN.1 CMS 签名 Bouncy CaSTLe 检索签名 R 和 S 元素