单击按钮下载文件

用户9998776

我有一个应用程序,单击按钮需要下载文本日志文件。我编写了后端 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);
            }
        }
费德里科·斯卡穆齐

我做过类似的事情..有点困难..我和你分享我的经验和我的代码..希望它对你有帮助!!

在您的 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;
            }
        }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章