点击按钮下载文件

时间:2018-06-28 12:09:24

标签: c# .net angular

我有一个应用程序,其中单击按钮需要下载文本日志文件。我编写了后端API,但是无法通过单击前端按钮将其连接。使用Angular 2和C#。我需要对component.ts文件进行哪些更改?

按钮代码:

<div class="col-lg-4"> <button type="button" class="btn btn-info pull-right" [hidden]="!dbtn" (click)="GetMigrationLog()" id="downloadLog" translate>Download Log</button>   </div>

这是我的后端api代码:

[Route("GetMigrationLog")]
        public IHttpActionResult GetMigrationLog()
        {
            try
            {
                IDBMigrationDataBo data = _serviceLocator.Resolve<IDBMigrationDataBo>();
                var result = data.GetMigrationLog();
                string logFileName = string.Format("Migration_{0}.txt", DateTime.Now.ToString("dd-MM-yyyy"));
                return StreamResponse(result, logFileName);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                return this.HandleError(ex);
            }
        }

1 个答案:

答案 0 :(得分:0)

我做了类似的事情..这有点困难..我与您分享了我的经验和代码..希望对您有帮助!

在您的html中 下载日志

在您的ts中:

 saveFile(id: string, name: string) {

    this._orderService.DownloadRicetta(id, name).then((result) => {
      this._toaster.pop('success', 'Download', 'Ricetta Scaricata con Successo');
    }).catch((err) => {
      this._toaster.pop('error', 'Download', 'Errore nel Download della Ricetta!')
      console.log(err);
    });

  }

在您的服务文件中:

首先导入一个软件包(已安装npm i --save file-saver @types/file-saver

import * as FileSaver from 'file-saver';

然后编写如下方法:

public async DownloadRicetta(id: string, name: string): Promise<Blob> {
    return new Promise<Blob>((resolve, reject) => {
      const headers = new HttpHeaders();
      headers.append('Accept', 'text/plain'); //just check the type you need

      this._http.get(environment.API_URL + `Order/${id}/Download/Ricetta`, { headers: headers, responseType: "blob", observe: 'response' })
        .subscribe(response => {
          try {
            let blob = this.saveToFileSystem(response, name);
            resolve(blob);
          } catch (error) {
            reject(error);
          }
        });
    });

  }





private saveToFileSystem(response, name: string): Blob {
    const contentDispositionHeader: string = response.headers.get('Content-Disposition');

    //for get original filename
    const parts: string[] = contentDispositionHeader.split(';');
    const filename = parts[1].trim().split('=')[1].trim();

    //get extension of the file
    const parts2: string[] = contentDispositionHeader.split('.');
    let ext = parts2[1];
    ext = ext.replace('"', '')
    //set mimetype
    let mimeType = Utils.extToMimeType(ext);

    const blob = new Blob([response.body], { type: mimeType });
    FileSaver.saveAs(blob, name + '_ricetta.' + ext);

    return blob;
  }

UTILS.ts文件:

export default class Utils {


  static extToMimeType(ext: string) {

    switch (ext) {
      case "pdf":
        return "application/pdf";
      case "jpg":
        return "image/jpg";
      case "png":
        return "image/png";
      case "txt":
        return "text/plain";
      default:
        return "";
    }
  }

}

还有后端(ASP.NET WEBAPI 2):

 [HttpGet]
        [Route("api/Order/{id}/Download/Ricetta")]
        public async Task<HttpResponseMessage> GetBookForHRM([FromUri] string id)
        {
            try
            {

                if (string.IsNullOrEmpty(id)) return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest };

                var order = await _orderService.FindAsync(xx => xx.Id == id);
                if (order == null) return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest };

                if (string.IsNullOrEmpty(order.RicettaUrl)) return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest };

                var user = await _aspNetService.FindAsync(xx => xx.Id == order.IdUser);
                if (user == null) return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest };

                var fileWithPath = $@"{user.GetUserRicettaDirectory()}/{order.RicettaUrl}";

                //converting Pdf file into bytes array  
                var dataBytes = File.ReadAllBytes(fileWithPath);
                //adding bytes to memory stream   
                var dataStream = new MemoryStream(dataBytes);

                HttpResponseMessage httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
                httpResponseMessage.Content = new StreamContent(dataStream);
                httpResponseMessage.Content.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
                httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                {
                    FileName = order.RicettaUrl.Trim()
                };
                httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");

                return httpResponseMessage;
            }
            catch (Exception ex)
            {
                _logger.LogException(ex);
                throw;
            }
        }