如何从 angular 应用程序创建和下载文件?斑点问题

问题描述

我无法从应用程序下载我生成文件代码现在看起来像这样:

async handleFileTranslateAction(): Promise<void> {
    this.progressspinerIsVisible = true
    this.originLanguageSelect = await this.languageService.getById(this.selectedOriginLanguage).toPromise()
    this.destinationLanguageSelect = await this.languageService.getById(this.selectedDestinationLanguage).toPromise()
    const result = await this.translateService.getTranslatedJson(
      this.fileInput.getFile(),this.originLanguageSelect,this.destinationLanguageSelect
    )
    const result2 = JSON.stringify(result)
    console.log(result2)
    const blob = new Blob([result2],{ type: 'text/json' });
    console.log(blob)
    this.fileDownloadUrl = this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob));
    // const blob = new Blob([result2],{ type: 'text/json' });
    // const url= window.URL.createObjectURL(blob);
    // window.open(url);
    const element: HTMLElement = document.getElementById('download-final-json-button') as HTMLElement;
    element.click()
    this.progressspinerIsVisible = false
  }

当我控制台日志结果 2 时,一切都显示正确,所有数据都很好,但是当我尝试控制台日志 blob 时,甚至当我下载文件时,我总是收到只包含以下内容文件

<!DOCTYPE html>
<html lang="en">
  <head>
    <Meta charset="utf-8" />
    <title>TachoTranslations</title>
    <base href="/" />
    <Meta name="viewport" content="width=device-width,initial-scale=1" />
    <link rel="icon" type="image/x-icon" href="favicon.ico" />
      <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
  <body class="mat-typography">
    <tt-root></tt-root>
  <script src="runtime.js" defer></script><script src="polyfills.js" defer></script><script src="styles.js" defer></script><script src="vendor.js" defer></script><script src="main.js" defer></script></body>
</html>

评论部分对我不起作用。我只想下载json文件

解决方法

你可以试试

   blob = new Blob([response],{ type: 'text/json' });
   const url = window.URL.createObjectURL(blob);
   window.open(url);

编辑。

类似的东西?

downloadFromLocal(path) {
    let link = document.createElement('a');
    link.setAttribute('type','hidden');
    link.href = `${path}`; //path to the file
    link.download = 'autocertificazione.docx';// name that the file takes
    document.body.appendChild(link);
    link.click();
    link.remove();
  }