【问题标题】:How to create downloadable file link for the file to download in ASP.net core如何为要在 ASP.net 核心中下载的文件创建可下载文件链接
【发布时间】:2019-01-14 05:25:33
【问题描述】:

以前我从 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 中,我可以直接将链接附加到锚标记的 href 属性,并自动点击它。所以我不需要将字节数组转换为url

这里的问题是我不知道如何使用 ASP.net 核心创建可下载的文件路径并将其发送到前端

我也想知道,发送Byte array 还是Sending the direct link 哪种方法更好?两者是否存在性能问题?

【问题讨论】:

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


    【解决方案1】:

    您的问题让您对角度前端和后端感到困惑 前端你可以使用mvc

    <a asp-controller="Controller"
       asp-action="Download" 
       asp-route-id="@Model.FileName">Download @Model.FileName</a> 
    

    或使用角度

    <a href="/Controller/Download?name=myFileName.ext">Download</a>
    <a [href]="ControllerRoute+'/Download?name='+fileName" download>Download {{fileName}}</a>
    

    好的,也许您的问题是您的操作(在控制器中)没有服务器文件 您需要返回带有 MediaType 的 HttpResponse,这只是一个示例,不要忘记代码的最佳实践

    [HttpGet]
    public HttpResponseMessage GetDownloadableFIle(string name)
    {
        try
        {
            var result = new HttpResponseMessage(HttpStatusCode.OK);
            var filePath = $"{MyRootPath}/{name}";
            var bytes = File.ReadAllBytes(filePath );
    
            result.Content = new ByteArrayContent(bytes);
    
            var mediaType = "application/octet-stream";
            result.Content.Headers.ContentType = new  System.Net.Http.Headers.MediaTypeHeaderValue(mediaType);
            return result;
        }
        catch (Exception ex)
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.InternalServerError, ex.ToString()));
        }
    }        
    

    【讨论】:

      【解决方案2】:

      如果您使用 api 响应作为文件数据

      在请求头中添加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});
          }
      

      【讨论】:

      • 感谢您的回复,我想,我在浪费这么多人的时间。但我的问题是服务器而不是 Angular。在前端我可以处理,但是从使用 ASP.net 核心的服务器,我怎样才能创建可下载的文件链接。再次感谢您的宝贵时间
      • 是的,我正在从服务器获取数据。我得到的响应没有问题。但问题是如何使用 ASP.net 核心创建可下载的文件链接
      猜你喜欢
      • 2012-12-18
      • 2012-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多