简体   繁体   English

在客户端创建和保存文件 - Angular

[英]Create and Save File on Client Side - Angular

Using angular 8, I would like to create below directory structure and let the user download it as a zip;使用 angular 8,我想创建以下目录结构并让用户将其下载为 zip;

- folder1
-- file1.txt
- folder2
-- file2.txt
readme.txt

I know how to create an individual file using Blob in angular like this link but I am not sure how to;我知道如何像这个链接一样使用 Blob 以角度创建单个文件,但我不确定如何;

  1. Create folders and above directory structure?创建文件夹和上面的目录结构?
  2. Zip the directory and download for the user as single zip file?压缩目录并将用户下载为单个 zip 文件?

all on client side in browser without using the backend API全部在浏览器客户端,不使用后端 API

I created a stackblitz as an example: https://stackblitz.com/edit/angular-9ommhs我创建了一个stackblitz作为例子: https ://stackblitz.com/edit/angular-9ommhs

import { Component } from '@angular/core';
import * as JSZip from 'jszip';
import fileSaver from 'file-saver';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  createZip() {
    const zip = new JSZip.default();
    // create a file
    zip.file("Hello.txt", "Hello World\n");
    // create a file and a folder
    zip.file("nested/hello.txt", "Hello World\n");
    zip.generateAsync({type:"blob"})
      .then(function(content) {
        // see FileSaver.js
         fileSaver.saveAs(content, "example.zip");
    });
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM