file-saver#saveAs TypeScript Examples

The following examples show how to use file-saver#saveAs. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.tsx    From assisted-ui-lib with Apache License 2.0 7 votes vote down vote up
downloadClusterInstallationLogs = async (
  addAlert: AlertsContextType['addAlert'],
  clusterId: string,
) => {
  try {
    if (ocmClient) {
      const { data } = await ClustersAPI.getPresignedForClusterFiles({
        clusterId,
        fileName: 'logs',
        hostId: undefined,
        logsType: 'all',
      });
      saveAs(data.url);
    } else {
      const { data, fileName } = await ClustersService.downloadLogs(clusterId);
      saveAs(data, fileName);
    }
  } catch (e) {
    handleApiError(e, async (e) => {
      addAlert({
        title: 'Could not download cluster installation logs.',
        message: getErrorMessage(e),
      });
    });
  }
}
Example #2
Source File: CustomDownloadFile.spec.ts    From next-basics with GNU General Public License v3.0 6 votes vote down vote up
describe("CustomDownloadFile", () => {
  it("should work", () => {
    CustomDownloadFile("aGVsbG8gd29yaw==", "abc.txt");
    expect((saveAs as jest.Mock).mock.calls[0][0] instanceof Blob).toEqual(
      true
    );

    expect((saveAs as jest.Mock).mock.calls[0][1]).toEqual("abc.txt");
  });
});
Example #3
Source File: csv.spec.ts    From lightning-terminal with MIT License 6 votes vote down vote up
describe('csv Util', () => {
  const csv = new CsvExporter();
  const swaps = [new Swap(loopListSwaps.swapsList[0])];

  it('should export using the .csv extension', () => {
    csv.export('swaps', Swap.csvColumns, swaps);
    expect(saveAs).toBeCalledWith(expect.any(Blob), 'swaps.csv');
  });

  it('should convert swap data to the correct string', () => {
    const actual = csv.convert(Swap.csvColumns, swaps);
    const expected = [
      '"Swap ID","Type","Amount","Status","Created On","Updated On"',
      '"f4eb118383c2b09d8c7289ce21c25900cfb4545d46c47ed23a31ad2aa57ce830","Loop Out","500000","Failed","Apr 8, 11:59 PM","Apr 9, 2:12 AM"',
    ].join('\n');
    expect(actual).toEqual(expected);
  });
});
Example #4
Source File: index.tsx    From visual-layout with MIT License 6 votes vote down vote up
exportCode = (
  project: ProjectService,
  codeConfig: CodeConfig = getInitCodeConfig(),
) => {
  const zip = new JSZip();
  Object.values(project.getPages()).forEach(page => {
    const files = generateCodeFiles(page, codeConfig);
    files.forEach(([key, { code }]) => {
      zip.folder(page.name)?.file(key, code);
    });
  });

  zip.generateAsync({ type: 'blob' }).then(function (content) {
    saveAs(content, `${project.name || 'Project'}.zip`);
  });
}
Example #5
Source File: ClusterDeploymentKubeconfigDownload.tsx    From assisted-ui-lib with Apache License 2.0 6 votes vote down vote up
ClusterDeploymentKubeconfigDownload = ({
  clusterDeployment,
  agentClusterInstall,
  fetchSecret,
}: ClusterDeploymentKubeconfigDownloadProps) => {
  const [clusterStatus] = getClusterStatus(agentClusterInstall);

  const handleKubeconfigDownload = async () => {
    const kubeconfigSecretName =
      agentClusterInstall.spec?.clusterMetadata?.adminKubeconfigSecretRef?.name;
    const kubeconfigSecretNamespace = clusterDeployment.metadata?.namespace;

    if (kubeconfigSecretName && kubeconfigSecretNamespace) {
      try {
        const kubeconfigSecret = await fetchSecret(kubeconfigSecretName, kubeconfigSecretNamespace);
        const kubeconfig = kubeconfigSecret.data?.kubeconfig;

        if (!kubeconfig) throw new Error('Kubeconfig is empty.');

        const blob = new Blob([atob(kubeconfig)], { type: 'text/plain;charset=utf-8' });
        saveAs(blob, 'kubeconfig.yaml');
      } catch (e) {
        console.error('Failed to fetch kubeconfig secret.', e);
      }
    }
  };

  return (
    <KubeconfigDownload
      handleDownload={handleKubeconfigDownload}
      clusterId={clusterDeployment.metadata?.uid || ''}
      status={clusterStatus}
    />
  );
}
Example #6
Source File: download.ts    From HappyIslandDesigner with MIT License 6 votes vote down vote up
export function downloadDataURLForiOSSafari(filename, data) {
  const image = new Image();
  image.src = data;
  image.addEventListener(
    'load',
    () => {
      saveAs(dataURLtoBlob(data), filename);
    }
  );
}
Example #7
Source File: ExportPackage.ts    From sp-site-designs-studio with MIT License 6 votes vote down vote up
public async download(): Promise<void> {
        if (this.hasSingleFile) {
            const fileName = this.allFiles[0];
            const fileContent = this._contents[fileName];
            const blob = new Blob([fileContent], { type: "octet/steam" });
            saveAs(blob, fileName);
        }
        else {
            const zip = new JSZip();
            this.allFiles.forEach(f => {
                zip.file(f, this._contents[f]);
            });
            await zip.generateAsync({ type: "blob" })
                .then((content) => {
                    saveAs(content, `${this.packageName}.zip`);
                });
        }
    }
Example #8
Source File: customer.effects.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
// Customer Bulk Delete
  @Effect()
  doCustomerExcel$: Observable<Action> = this.action$.pipe(
    ofType(actions.ActionTypes.GET_CUSTOMER_EXCEL),
    map((action: actions.DoCustomerExcel) => action.payload),
    switchMap(state => {
      return this.Service.customerExcel(state).pipe(
        tap(data => {
          const filename = 'CustomerExcel_' + Date.now() + '.xlsx';
          const blob = new Blob([data], { type: 'text/xlsx' });
          saveAs(blob, filename);
        }),
        switchMap(user => [new actions.DoCustomerExcelSuccess(user)]),
        catchError(error => of(new actions.DoCustomerExcelFail(error)))
      );
    })
  );
Example #9
Source File: CustomDownloadFile.ts    From next-basics with GNU General Public License v3.0 6 votes vote down vote up
export function CustomDownloadFile(
  dataURI: string,
  filename: string,
  options: Record<string, any> = {}
): void {
  const { mediaType } = options;

  const byteString = window.atob(dataURI);
  const ab = new ArrayBuffer(byteString.length);
  const ia = new Uint8Array(ab);

  for (let i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }
  const blob = new Blob([ia], { type: mediaType });

  saveAs(blob, filename);
}
Example #10
Source File: theme-editor.ts    From elemental4 with GNU General Public License v3.0 6 votes vote down vote up
export async function downloadDeveloperTheme() {
  var zip = new JSZip();

  const finalJSON = {
    ...devTheme.json
  };

  if (devTheme.style.trim() !== '') {
    zip.file('style.css', devTheme.style)
    finalJSON.styles = './style.css';
  }
  if (devTheme.sketch.trim() !== '' && devTheme.sketch.replace(/\s/g,'') !== defaultTheme.sketch.replace(/\s/g,'')) {
    zip.file('sketch.js', devTheme.sketch)
    finalJSON.sketch = './sketch.js';
  }
  zip.file('elemental.json', JSON.stringify(finalJSON, null, 2))

  zip.generateAsync({ type: "blob" })
    .then(function(blob) {
      saveAs(blob, 'theme.zip');
    });
}
Example #11
Source File: product.effect.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
// Product Excel
  @Effect()
  doProductExcel$: Observable<Action> = this.action$.pipe(
    ofType(actions.ActionTypes.GET_PRODUCT_EXCEL),
    map((action: actions.DoProductExcel) => action.payload),
    switchMap(state => {
      return this.service.productExcel(state).pipe(
        tap(data => {
          const filename = 'ProductExcel_' + Date.now() + '.xlsx';
          const blob = new Blob([data], { type: 'text/xlsx' });
          saveAs(blob, filename);
        }),
        switchMap(user => [new actions.DoProductExcelSuccess(user)]),
        catchError(error => of(new actions.DoProductExcelFail(error)))
      );
    })
  );
Example #12
Source File: Export.tsx    From moodtracker with MIT License 6 votes vote down vote up
downloadCsv = (
  dataType: DataType,
  denormalizedData: DenormalizedData
) => {
  const columns: Set<string> = new Set();
  const flattenedDenormalizedData: FlattenedDatum[] = [];

  for (const datum of denormalizedData) {
    const flattenedDatum: FlattenedDatum = {};
    for (const [key, val] of Object.entries(datum)) {
      if (typeof val !== "object") {
        flattenedDatum[key] = val;
        columns.add(key);
        continue;
      }
      for (const [k, v] of Object.entries(
        val as Record<string, number | string>
      )) {
        const flattenedKey = `${key}:${k}`;
        flattenedDatum[flattenedKey] = v;
        columns.add(flattenedKey);
      }
    }
    flattenedDenormalizedData.push(flattenedDatum);
  }

  saveAs(
    new Blob([unparse(flattenedDenormalizedData, { columns: [...columns] })], {
      type: "text/csv",
    }),
    createFilename(dataType, "csv")
  );
}
Example #13
Source File: debug.ts    From novel-downloader with GNU Affero General Public License v3.0 6 votes vote down vote up
export async function debug() {
  const rule = await getRule();
  let book;
  if (typeof (window as GmWindow)._book !== "undefined") {
    book = (window as GmWindow)._book;
  } else {
    book = await rule.bookParse();
  }
  (unsafeWindow as UnsafeWindow).rule = rule;
  (unsafeWindow as UnsafeWindow).book = book;
  (window as GmWindow)._book = book;

  (unsafeWindow as UnsafeWindow).saveAs = saveAs;
  const { parse, fetchAndParse, gfetchAndParse } = await import(
    "./lib/readability"
  );
  (unsafeWindow as UnsafeWindow).readability = {
    parse,
    fetchAndParse,
    gfetchAndParse,
  };

  (unsafeWindow as UnsafeWindow).stopController = (
    window as GmWindow
  ).stopController;
  return;
}
Example #14
Source File: map-generator.ts    From mapbox-gl-export with MIT License 6 votes vote down vote up
/**
   * Convert canvas to PNG
   * @param canvas Canvas element
   * @param fileName file name
   */
  private toPNG(canvas: HTMLCanvasElement, fileName: string) {
    canvas.toBlob((blob) => {
      // @ts-ignore
      saveAs(blob, fileName);
    });
  }
Example #15
Source File: dashboard.component.ts    From ng-application-builder with MIT License 6 votes vote down vote up
downloadApp() {
    this.showSpinner = true;
    this.dataService.downloadApp(this.appConfiguration).subscribe((response: any) => {
      saveAs(response, this.appConfiguration.name + '.zip');
      console.log(response);
      this.showSpinner = false;
    }, (err) => {
      this.showSpinner = false;
      alert(JSON.stringify(err));
      console.error(err);
    });

  }
Example #16
Source File: PanelInspector.tsx    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
exportCsv = (dataFrame: DataFrame) => {
    const dataFrameCsv = toCSV([dataFrame]);

    const blob = new Blob([dataFrameCsv], {
      type: 'application/csv;charset=utf-8',
    });

    saveAs(blob, dataFrame.name + '-' + new Date().getUTCDate() + '.csv');
  };
Example #17
Source File: helpers.ts    From ngm with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
export async function downloadGeometry(entity) {
  if (!entity) return;
  const geometries = new EntityCollection();
  const name = entity.name.replace(' ', '_');
  geometries.add(entity);
  const exportResult: exportKmlResultKml = <exportKmlResultKml> await exportKml({
    entities: geometries,
    time: julianDate
  });
  let kml: string = exportResult.kml;
  kml = extendKmlWithProperties(kml, geometries);
  const blob = new Blob([kml], {type: 'application/vnd.google-earth.kml+xml'});
  saveAs(blob, `swissgeol_geometry_${name}.kml`);
}
Example #18
Source File: orders.effects.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
// Order Excel
  @Effect()
  doOrderExcel$: Observable<Action> = this.action$.pipe(
    ofType(actions.ActionTypes.GET_ORDER_EXCEL),
    map((action: actions.DoOrderExcel) => action.payload),
    switchMap(state => {
      return this.apiCli.orderExcel(state).pipe(
        tap(data => {
          const filename = 'OrderExcel_' + Date.now() + '.xlsx';
          const blob = new Blob([data], { type: 'text/xlsx' });
          saveAs(blob, filename);
        }),
        switchMap(user => [new actions.DoOrderExcelSuccess(user)]),
        catchError(error => of(new actions.DoOrderExcelFail(error)))
      );
    })
  );
Example #19
Source File: component.ts    From alauda-ui with MIT License 6 votes vote down vote up
exportColors() {
    const colors = `:root {${this.schema.toString()} }`;

    saveAs(
      new Blob([colors], {
        type: 'text/plain;charset=utf-8',
      }),
      'aui-colors.css',
    );
  }
Example #20
Source File: Export.tsx    From moodtracker with MIT License 6 votes vote down vote up
downloadJson = (
  dataType: DataType,
  denormalizedData: DenormalizedData
) => {
  saveAs(
    new Blob([JSON.stringify(denormalizedData)], {
      type: "application/json",
    }),
    createFilename(dataType, "json")
  );
}
Example #21
Source File: fetch.ts    From datart with Apache License 2.0 5 votes vote down vote up
dealFileSave = (data, headers) => {
  const fileNames = /filename[^;\n=]*=((['"]).*?\2|[^;\n]*)/g.exec(
    headers?.['content-disposition'] || '',
  );
  const encodeFileName = decodeURIComponent(fileNames?.[1] || '');
  const blob = new Blob([data], { type: '**application/octet-stream**' });
  saveAs(blob, String(encodeFileName?.replaceAll('"', '')) || 'unknown.xlsx');
}
Example #22
Source File: app.component.ts    From sdkgen with MIT License 5 votes vote down vote up
downloadTarget(target: SdkgenTarget) {
    if (!this.state) {
      return;
    }

    let source;
    let fileName;

    switch (target) {
      case "typescript_nodeserver": {
        source = generateNodeServerSource(this.state.astRoot);
        fileName = "node-server.ts";
        break;
      }

      case "typescript_nodeclient": {
        source = generateNodeClientSource(this.state.astRoot);
        fileName = "node-client.ts";
        break;
      }

      case "typescript_web": {
        source = generateBrowserClientSource(this.state.astRoot);
        fileName = "web-client.ts";
        break;
      }

      case "typescript_interfaces": {
        source = generateTypescriptInterfaces(this.state.astRoot);
        fileName = "interfaces.ts";
        break;
      }

      case "flutter": {
        source = generateDartClientSource(this.state.astRoot);
        fileName = "flutter-client.dart";
        break;
      }

      case "csharp_server": {
        source = generateCSharpServerSource(this.state.astRoot);
        fileName = "csharp-server.cs";
        break;
      }

      case "fsharp_server": {
        source = generateFSharpServerSource(this.state.astRoot);
        fileName = "fsharp-server.fs";
        break;
      }

      case "kotlin_android": {
        source = generateAndroidClientSource(this.state.astRoot, true);
        fileName = "android-client.kt";
        break;
      }

      case "kotlin_android_without_callbacks": {
        source = generateAndroidClientSource(this.state.astRoot, false);
        fileName = "android-client-no-callbacks.kt";
        break;
      }

      case "swift_ios": {
        source = generateSwiftClientSource(this.state.astRoot, false);
        fileName = "ios-client.swift";
        break;
      }

      case "rxswift_ios": {
        source = generateSwiftClientSource(this.state.astRoot, true);
        fileName = "ios-client-rx.swift";
        break;
      }
    }

    saveAs(new Blob([source], { type: "application/octet-stream" }), fileName);
  }
Example #23
Source File: file_export.ts    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
export function saveSaveBlob(payload: any, fname: string) {
  const blob = new Blob([payload], { type: 'text/csv;charset=utf-8;header=present;' });
  saveAs(blob, fname);
}
Example #24
Source File: KubeconfigDownload.tsx    From assisted-ui-lib with Apache License 2.0 5 votes vote down vote up
KubeconfigDownload: React.FC<KubeconfigDownloadProps> = ({
  clusterId,
  status,
  id,
  handleDownload,
}) => {
  const { addAlert } = useAlerts();

  const download = React.useCallback(
    async (clusterId: Cluster['id']) => {
      try {
        if (ocmClient) {
          const { data } = await ClustersAPI.getPresignedForClusterCredentials({
            clusterId,
            fileName: 'kubeconfig',
          });
          saveAs(data.url);
        } else {
          const response = await ClustersAPI.downloadClusterCredentials(clusterId, 'kubeconfig');
          const fileName = getKubeconfigFileName(response.headers);

          saveAs(response.data, fileName);
        }
      } catch (e) {
        handleApiError(e, async (e) => {
          addAlert({ title: 'Could not download kubeconfig', message: getErrorMessage(e) });
        });
      }
    },
    [addAlert],
  );

  return (
    <Button
      variant={ButtonVariant.secondary}
      onClick={handleDownload || (() => download(clusterId))}
      isDisabled={!canDownloadKubeconfig(status)}
      id={id}
      data-testid={id}
    >
      Download kubeconfig
    </Button>
  );
}
Example #25
Source File: SaveProvisionedDashboardForm.tsx    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
SaveProvisionedDashboardForm: React.FC<SaveDashboardFormProps> = ({ dashboard, onCancel }) => {
  const dashboardJSON = useMemo(() => {
    const clone = dashboard.getSaveModelClone();
    delete clone.id;
    return clone;
  }, [dashboard]);

  const getClipboardText = useCallback(() => {
    return JSON.stringify(dashboardJSON, null, 2);
  }, [dashboard]);

  const saveToFile = useCallback(() => {
    const blob = new Blob([JSON.stringify(dashboardJSON, null, 2)], {
      type: 'application/json;charset=utf-8',
    });
    saveAs(blob, dashboard.title + '-' + new Date().getTime() + '.json');
  }, [dashboardJSON]);

  return (
    <>
      <VerticalGroup spacing="lg">
        <small>
          This dashboard cannot be saved from Grafana's UI since it has been provisioned from another source. Copy the
          JSON or save it to a file below. Then you can update your dashboard in corresponding provisioning source.
          <br />
          <i>
            See{' '}
            <a
              className="external-link"
              href="http://docs.grafana.org/administration/provisioning/#dashboards"
              target="_blank"
            >
              documentation
            </a>{' '}
            for more information about provisioning.
          </i>
        </small>
        <div>
          <strong>File path: </strong> {dashboard.meta.provisionedExternalId}
        </div>
        <div
          className={css`
            padding: 8px 16px;
            background: black;
            height: 400px;
          `}
        >
          <CustomScrollbar>
            <JSONFormatter json={dashboardJSON} open={1} />
          </CustomScrollbar>
        </div>
        <HorizontalGroup>
          <CopyToClipboard text={getClipboardText} elType={Button}>
            Copy JSON to clipboard
          </CopyToClipboard>
          <Button onClick={saveToFile}>Save JSON to file</Button>
          <Forms.Button variant="secondary" onClick={onCancel}>
            Cancel
          </Forms.Button>
        </HorizontalGroup>
      </VerticalGroup>
    </>
  );
}
Example #26
Source File: saveFile.ts    From nextclade with MIT License 5 votes vote down vote up
export function saveBlobFile(content: Blob, filename: string) {
  saveAs(content, filename)
}
Example #27
Source File: AuthContainer.ts    From casper-clarity with Apache License 2.0 5 votes vote down vote up
function saveToFile(content: string, filename: string) {
  let blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
  saveAs(blob, filename);
}
Example #28
Source File: ShareExport.tsx    From grafana-chinese with Apache License 2.0 5 votes vote down vote up
openSaveAsDialog = (dash: any) => {
    const dashboardJsonPretty = JSON.stringify(dash, null, 2);
    const blob = new Blob([dashboardJsonPretty], {
      type: 'application/json;charset=utf-8',
    });
    const time = new Date().getTime();
    saveAs(blob, `${dash.title}-${time}.json`);
  };
Example #29
Source File: zip.ts    From novel-downloader with GNU Affero General Public License v3.0 5 votes vote down vote up
public constructor(
    filename: string,
    stream: boolean,
    mimetype = "application/zip"
  ) {
    log.info(
      `[fflateZip] filename: ${filename}, stream: ${stream}, streamSaver.supported: ${streamSaver.supported}`
    );
    const self = this;

    this.filename = filename;
    if (streamSaver.supported) {
      this.stream = stream;
    } else {
      this.stream = false;
    }

    let writer: WritableStreamDefaultWriter<Uint8Array>;
    if (this.stream) {
      const fileStream = streamSaver.createWriteStream(self.filename);
      writer =
        fileStream.getWriter() as WritableStreamDefaultWriter<Uint8Array>;
    }

    this.savedZip = new Zip((err, dat, final) => {
      if (err) {
        log.error(err);
        log.trace(err);
        if (self.stream) {
          writer.abort();
        }
        throw err;
      }

      if (self.stream) {
        writer.write(dat);
      } else {
        self.zipOut = new Blob([self.zipOut, dat], { type: mimetype });
      }

      if (final) {
        if (self.stream) {
          writer.close();
          log.info("[fflateZip] ZIP生成完毕");
        } else {
          nonStream();
        }
      }

      function nonStream() {
        log.info("[fflateZip] ZIP生成完毕,文件大小:" + self.zipOut.size);
        try {
          saveAs(self.zipOut, self.filename);
          self.zipOut = new Blob([], { type: "application/zip" });
        } catch (error) {
          log.error("[fflateZip]" + error);
          log.trace(error);
        }
      }
    });
  }