Giter Site home page Giter Site logo

cipchk / ngx-filesaver Goto Github PK

View Code? Open in Web Editor NEW
86.0 4.0 18.0 3.66 MB

Simple file save with FileSaver.js

Home Page: https://cipchk.github.io/ngx-filesaver/

License: MIT License

JavaScript 8.65% TypeScript 55.02% HTML 36.33%
file-saver filesaver angular angular-component

ngx-filesaver's Introduction

ngx-filesaver

Simple file save with FileSaver.js

NPM version Ci codecov

中文版

Examples

Installation

$ npm install file-saver ngx-filesaver
# Or when using yarn
$ yarn add file-saver ngx-filesaver
# Or when using pnpm
$ pnpm install file-saver ngx-filesaver

Add the FileSaverModule module to your project:

import { FileSaverModule } from 'ngx-filesaver';

@NgModule({
  imports: [FileSaverModule],
})
export class AppModule {}

Instructions

There are two ways to save a file: using FileSaverService.save() or using the fileSaver directive.

1、FileSaverService

constructor(private _http: Http, private _FileSaverService: FileSaverService) {
}

onSave() {
  this._http.get('demo.pdf', {
    responseType: ResponseContentType.Blob // This must be a Blob type
  }).subscribe(res => {
    this._FileSaverService.save((<any>res)._body, fileName);
  });
}

2、fileSaver directive

Configuration example

<button
  type="button"
  fileSaver
  [method]="'GET'"
  [fileName]="'中文pdf.pdf'"
  [url]="'assets/files/demo.pdf'"
  [header]="{ token: 'demo' }"
  [query]="{ pi: 1, name: 'demo' }"
  (success)="onSuc($event)"
  (error)="onErr($event)"
>
  Download PDF
</button>

fileSaver: the directive name Parameters

Parameter Description Type Default
method Request method type string GET
url Request URL string -
fileName Filename when downloading string -
query Additional query parameters. Equivalent to params value string -
header Header configuration. Usually used for especifying access tokens any -
fsOptions FileSaver.js config, can be set autoBom value FileSaverOptions -
success Download success callback EventEmitter<HttpResponse<Blob>> -
error Download error callback EventEmitter<any> -

Custom HTTP type

<button type="button" fileSaver [http]="onRemote('pdf', true)">Download PDF</button>
onRemote(type: string, fromRemote: boolean): Observable<Response> {
  return this._http.get(`assets/files/demo.${type}`, {
    responseType: ResponseContentType.Blob
  }).map(response => {
    response.headers.set('filename', `demo.${type}`)
    return response;
  });
}

About filenames

The name for the downloaded file is obtained with the following priority:

  1. fileName
  2. response.headers.get('filename')
  3. response.headers.get('x-filename')。

If you are requesting a CORS address, you need to pay attention to the request headers. Setting Access-Control-Allow-Headers: filename should be sufficient

Class Name

Class Name Description
filesaver__not-support Not Supported Browsers
filesaver__disabled During http request

Configuring CommonJS dependencies

WARNING in node_modules/ngx-filesaver/ivy_ngcc/fesm2015/ngx-filesaver.js depends on file-saver. CommonJS or AMD dependencies can cause optimization bailouts.

We cannot change this, the only way is to ignore it:

"build": {
  "builder": "@angular-devkit/build-angular:browser",
  "options": {
     "allowedCommonJsDependencies": [
        "file-saver"
     ]
     ...
   }
   ...
},

ngx-filesaver's People

Contributors

angular-cli avatar arturovt avatar cipchk avatar ioxua avatar mo-gong avatar tomassurek avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

ngx-filesaver's Issues

Cannot find module '@angular/common/http' from '../../node_modules/ngx-filesaver/fesm2020/ngx-filesaver.mjs'

We have an Angular app that I recently upgraded to Angular 15 (from Angular 11). After upgrading - running the unit test case we get the following error:

    Cannot find module '@angular/common/http' from '../../node_modules/ngx-filesaver/fesm2020/ngx-filesaver.mjs'

    Require stack:
      /<<path>>/node_modules/ngx-filesaver/fesm2020/ngx-filesaver.mjs
      src/app/utils/utils-service.ts
      src/app/utils/index.ts
      src/app/services/actions-listener.service.ts
      src/app/services/index.ts

ng version output:

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/


Angular CLI: 15.2.10
Node: 18.18.0
Package Manager: npm 9.8.1
OS: darwin arm64

Angular: 15.2.10
... animations, cli, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                            Version
------------------------------------------------------------
@angular-devkit/architect          0.1502.10
@angular-devkit/build-angular      15.2.10
@angular-devkit/core               15.2.10
@angular-devkit/schematics         15.2.10
@angular/cdk                       15.2.9
@angular/material                  15.2.9
@angular/material-moment-adapter   15.2.9
@schematics/angular                15.2.10
rxjs                               6.5.5
typescript                         4.9.5

Package json has following version of ngx-filesaver:

"ngx-filesaver": "15.0.0",

The Angular project is part of a mono repo. The node_modules in the root folder does not contain the @angular/common but the node_modules of the Angular app does contain the @angular/common folder.

Any pointers on what could be wrong?

I also tried importing HttpClientModule and the FileSaverModule in my main app module but it did not help. It was not required in Angular version 11.

Upgrade to Angular 16 errors in compilation

Following errors after upgrading to Angular 16

✖ Failed to compile.
✔ Browser application bundle generation complete.

33 unchanged chunks

Build at: 2023-09-22T10:34:58.228Z - Hash: 49bb4f0e82d1526b - Time: 1506ms

./node_modules/ngx-filesaver/fesm2022/ngx-filesaver.mjs:95:51-57 - Error: export 'filter' (imported as 'filter') was not found in 'rxjs' (possible exports: ArgumentOutOfRangeError, AsyncSubject, BehaviorSubject, ConnectableObservable, EMPTY, EmptyError, GroupedObservable, NEVER, Notification, NotificationKind, ObjectUnsubscribedError, Observable, ReplaySubject, Scheduler, Subject, Subscriber, Subscription, TimeoutError, UnsubscriptionError, VirtualAction, VirtualTimeScheduler, animationFrame, animationFrameScheduler, asap, asapScheduler, async, asyncScheduler, bindCallback, bindNodeCallback, combineLatest, concat, config, defer, empty, forkJoin, from, fromEvent, fromEventPattern, generate, identity, iif, interval, isObservable, merge, never, noop, observable, of, onErrorResumeNext, pairs, partition, pipe, queue, queueScheduler, race, range, scheduled, throwError, timer, using, zip)

./node_modules/ngx-filesaver/fesm2022/ngx-filesaver.mjs:95:96-105 - Error: export 'takeUntil' (imported as 'takeUntil') was not found in 'rxjs' (possible exports: ArgumentOutOfRangeError, AsyncSubject, BehaviorSubject, ConnectableObservable, EMPTY, EmptyError, GroupedObservable, NEVER, Notification, NotificationKind, ObjectUnsubscribedError, Observable, ReplaySubject, Scheduler, Subject, Subscriber, Subscription, TimeoutError, UnsubscriptionError, VirtualAction, VirtualTimeScheduler, animationFrame, animationFrameScheduler, asap, asapScheduler, async, asyncScheduler, bindCallback, bindNodeCallback, combineLatest, concat, config, defer, empty, forkJoin, from, fromEvent, fromEventPattern, generate, identity, iif, interval, isObservable, merge, never, noop, observable, of, onErrorResumeNext, pairs, partition, pipe, queue, queueScheduler, race, range, scheduled, throwError, timer, using, zip)

./node_modules/ngx-filesaver/fesm2022/ngx-filesaver.mjs:111:15-24 - Error: export 'takeUntil' (imported as 'takeUntil') was not found in 'rxjs' (possible exports: ArgumentOutOfRangeError, AsyncSubject, BehaviorSubject, ConnectableObservable, EMPTY, EmptyError, GroupedObservable, NEVER, Notification, NotificationKind, ObjectUnsubscribedError, Observable, ReplaySubject, Scheduler, Subject, Subscriber, Subscription, TimeoutError, UnsubscriptionError, VirtualAction, VirtualTimeScheduler, animationFrame, animationFrameScheduler, asap, asapScheduler, async, asyncScheduler, bindCallback, bindNodeCallback, combineLatest, concat, config, defer, empty, forkJoin, from, fromEvent, fromEventPattern, generate, identity, iif, interval, isObservable, merge, never, noop, observable, of, onErrorResumeNext, pairs, partition, pipe, queue, queueScheduler, race, range, scheduled, throwError, timer, using, zip)

上传后可以下载,过一会就不行了

我按照你的方法angular4不兼容性就把文件复制进来,调用下载文件的地址是阿里云oss存的,但是我上传后可以下载,过一会就报错了,请问这是什么原因,代码 // 保存图片到本地 saveImageToLocal(image: any, fromRemote: boolean) { const fileName =图片; this.log.debug('show URL', image.imageUrl); if (fromRemote) { this._httpClient.get(${image.imageUrl}, { observe: 'response', responseType: 'blob' }).subscribe(res => { this.log.debug('show res:', res); this._FileSaverService.save(res.body, fileName); }); return; } }
报的错误Access to XMLHttpRequest at 'http://vehicles-data-center.oss-cn-hangzhou.aliyuncs.com/%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B.png' from origin 'http://localhost:57767' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Assembly call problems

I have doubts in the assembly of the call to assemble my excel.
I have a json where it has a parent array and the child and the child has other children.

ex:

export interface ObjectiveResult {
  keyName: string;
  dateStart: Date;
  dateEnd: Date;
  contents: KeyResult[];
}
export interface KeyResult {
  keyName: string;
  reporter?: RepoAssign[];
}

What would be the parameter to be passed to assemble the export?

Add support for Angular 16

Now that Angular 16 has been released, are there any plans to release a new version that supports Angular 16?

file-saver not installed automatically as dependency

When ngx-filesaver is installed, the package file-saver is not installed.
As mentioned by the documentation, it is necessary to execute npm i file-saver as well.
Could package.json be changed so that the necessary package file-saver is installed automatically ?
Adding the package as a dependency could do, I think. For now, there is only tslib :
image

callbacks?

How do I access the success and error callbacks using FileSaverService (not directive)?

got an error when trying to build.

Angular 6, ngx-filesaver 2.0.1

The error message is:

ERROR in Error during template compile of 'NgModule'
Function calls are not supported in decorators but 'ɵmakeDecorator' was called.
: Unexpected value 'FileSaverModule in /Users/projects/j5/node_modules/ngx-filesaver/filesaver.d.ts' imported by the module 'J5AppModule in /Users/projects/j5/src/main/webapp/app/app.module.ts'. Please add a @NgModule annotation.

Bump to ngx-filesaver 15.0.1 results in Errors

We are using this package in our Angular 15 application and during a regular maintenance task we updated the package from 15.0.0 to 15.0.1. However, the version bump results in errors:
image

Error: export 'takeUntil' (imported as 'takeUntil') was not found in 'rxjs' (possible exports: Ar
gumentOutOfRangeError, AsyncSubject, BehaviorSubject, ConnectableObservable, EMPTY, EmptyError, GroupedObservable, NEVER, Notification, NotificationKind, ObjectUnsub
scribedError, Observable, ReplaySubject, Scheduler, Subject, Subscriber, Subscription, TimeoutError, UnsubscriptionError, VirtualAction, VirtualTimeScheduler, animat
ionFrame, animationFrameScheduler, asap, asapScheduler, async, asyncScheduler, bindCallback, bindNodeCallback, combineLatest, concat, config, defer, empty, forkJoin,
 from, fromEvent, fromEventPattern, generate, identity, iif, interval, isObservable, merge, never, noop, observable, of, onErrorResumeNext, pairs, partition, pipe, q
ueue, queueScheduler, race, range, scheduled, throwError, timer, using, zip)

I suspect it has to do with this commit b2978bd.

I tried to setup a new angular project, import ngx-filesaver 15.0.1 and rxjs takeuntil directly but it does not result in the error on its own.
But If I manually set the rxjs version of the project to ^6.6.7

"rxjs": "^6.6.7",

and then using the older import for rxjs in my component, it will fail with the same error message.

import { Component } from '@angular/core';
import { FileSaverService } from 'ngx-filesaver';
import { fromEvent, interval } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'angular-tour-of-heroes';

  public constructor (private _FileSaverService: FileSaverService)
  {
    console.log(_FileSaverService);

    const source = interval(1000);
    const clicks = fromEvent(document, 'click');
    const result = source.pipe(takeUntil(clicks));
    result.subscribe(x => console.log(x));
  }
}

Is the newly added imports to lib/src/filesaver.directive.ts a breaking change?
In version 6.6.7 the 'takeUntil' was still imported like this: import { takeUntil } from 'rxjs/operators'; (which we imported from there)
Might be helpful.

Save file without extension

I tried to download files without extension using the service but it is appending .txt extension automatically.
I also tried to download files with .cred extension but when download starts it showing .txt extension.

File download without extenstion
this.fileSaverService.save(file, 'credentials');

File download with extenstion
this.fileSaverService.save(file, 'credentials', 'cred');

I also tried passing type in a blob but still, the file is saving with .txt extension.

'/ɵɵdefineInjectable' in dist

I've followed the guide and this message occurs :

./node_modules/ngx-filesaver/fesm5/ngx-filesaver.js 54:39-57
"export 'ɵɵdefineInjectable' was not found in '@angular/core'.

Saving video files corrupts them

Hey,

So I have added ngx-filesaver to my angular application and it downloads images fine, but with videos it doesn't work properly. I does download the video, but when I try to play it, it says the video is corrupted. I can play the video in the browser (before downloading). The code I have looks like this:

public download(asset: SimpleResourceBase): void {
  const parts = asset.secureUrl.split('.');
  if (parts.length === 1) return;

  const extension = parts[parts.length - 1];

  this.httpClient
    .get<Blob>(asset.secureUrl, {
      observe: 'body',
      responseType: 'blob' as 'json',
    })
    .subscribe((response) => {
      console.log(response);
      this.fileSaverService.save(
        <any>response,
        `${asset.fileName}.${extension}`
      );
    });
}

and the SimpleResourceBase looks like this:

export declare class SimpleResourceBase {
    id: string;
    publicId: string;
    normalisePublicId: string;
    folder: string;
    fileName: string;
    indexUrl: string;
    url: string;
    secureUrl: string;
}

Is there something I have to do differently, to get the video to download?

Compilation error: Property '"method"' is incompatible with index signature.

I am using Angular core 15.2.0, and tried 14.0.0, 15.0.0 and 16.0.0 versions of ngx-filesaver and all got following error:

Error: node_modules/ngx-filesaver/src/filesaver.directive.d.ts:30:94 - error TS2344: Type '{ method: { alias: "method"; required: false; }; http: { alias: "http"; required: false; }; query: { alias: "query"; required: false; }; header: { alias: "header"; required: false; }; url: { alias: "url"; required: true; }; fileName: { ...; }; fsOptions: { ...; }; }' does not satisfy the constraint '{ [key: string]: string; }'.

Property '"method"' is incompatible with index signature.

Type '{ alias: "method"; required: false; }' is not assignable to type 'string'.

30 static ɵdir: i0.ɵɵDirectiveDeclaration<FileSaverDirective, "[fileSaver]", ["fileSaver"], { "method": { "alias": "method"; "required": false; }; "http": { "alias": "http"; "required": false; }; "query": { "alias": "query"; "required": false; }; "header": { "alias": "header"; "required": false; }; "url": { "alias": "url"; "required": true; }; "fileName": { "alias": "fileName"; "required": false; }; "fsOptions": { "alias": "fsOptions"; "required": false; }; }, { "success": "success"; "error": "error"; }, never, never, true, never>;

Seems the grammar is not compatible with Angular. What am I missing?

Error when import fileSaverModule

I work with angular 7, I installed the ngx-fileSaver library version 8.1.0 when I import the fileSaverModule I get the following error.

ngx-filesaver.js:55 Uncaught TypeError: Object(...) is not a function
at ngx-filesaver.js:55
at Module../node_modules/ngx-filesaver/fesm5/ngx-filesaver.js (ngx-filesaver.js:60)
at webpack_require (bootstrap:83)
at Module../src/app/modules/swt-toolbox/com/swallow/utils/common.service.ts (common-util.service.ts:22)
at webpack_require (bootstrap:83)
at Module../src/app/modules/swt-toolbox/com/swallow/controls/title-window.component.ts (swt-vdividedbox.component.ts:70)
at webpack_require (bootstrap:83)
at Module../src/app/modules/swt-toolbox/index.ts (index.ts:1)
at webpack_require (bootstrap:83)
at Module../src/app/app.component.ts (main.js:953)

Upgrade my project and my external third library from Angular 11 to 12 fails because of a dependency to "ngx-filesaver" in my library

I have two Angular projects :

  • the main Angular project
  • an external third library

The external third library has a dependency to the ngx-filesaver library.

With Angular 11 ("@angular/core": "~11.2.14", "ngx-filesaver": "^11.0.0"), everything is OK.

After upgrading to Angular 12 ("@angular/core": "~12.2.17", "ngx-filesaver": "^12.0.0"), I have an error after launching the ng serve command:

C:\Users\my-path\node_modules\@angular\compiler-cli\ngcc\src\entry_point_finder\targeted_entry_point_finder.js:40
                throw new Error("The target entry-point \"" + invalidTarget.entryPoint.name + "\" has missing dependencies:\n" +
                ^

Error: The target entry-point "my-external-third-library" has missing dependencies:
 - ngx-toastr/public_api
 - ngx-filesaver/index

(note the ngx-toastr library is also causing a similar issue)

Any idea of what's wrong ?

See my post on StackOverflow for a complete description of the issue.

ERROR in Metadata version mismatch

Hi, thanks for the package.

Got an error when building the project saying:

ERROR in Metadata version mismatch for module /Users/gang_fang/Desktop/CMSA-frontend/node_modules/ngx-filesaver/index.d.ts, found version 4, expected 3

Fixed by changing version 34 to 3 in all *.metadata.json file within ngx-filesaver directory.

About ES Modules

Hi,

Wouldn't a solution to fix the:

WARNING in node_modules/ngx-filesaver/ivy_ngcc/fesm2015/ngx-filesaver.js depends on file-saver. CommonJS or AMD dependencies can cause optimization bailouts.

To use the package: file-saver-es instead?

Downloaded rar file has very small size

When downloading a file using file-saver package the file is getting downloaded correctly with size 600kb
with this code :
saveAs(fileUrl, fileName);

But when I'm using ngx-filesaver the file dowloaded is 65kb and the unrar process is giving an errror
this._FileSaverService.save(fileUrl, fileName);

Any idea what I might be doing wrong? or is it some bug?

The file I'm using is a rar file which is being served by a nginx server upon calling the fileUrl.

"save" does not have option to set "disableAutoBOM" flag.

"save" does not have the option to set "disableAutoBOM" flag.

The saveAs function of the fileSaver library has a disableAutoBOM flag, which is default to false. I need to set this flag to true. However, this library does not have this option.

Request to add this feature.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.