Giter Club home page Giter Club logo

ng2-file-input's Introduction

Join the chat at https://gitter.im/bergben/bergben

Not actively maintained anymore, looking for maintainer

Unfortunately I don't have time to actively maintain my open source repos anymore. If anyone wants to take over, feel free to contact me anytime, I'd be happy if this project still finds use.

ng2-file-input

Angular 4 and 5 component that implements a drag and drop or select file selection, including preview.

Demo

A simple demo is available as a plnkr: http://plnkr.co/edit/eU7VM4j74ljN36bnZbPP?p=preview

Breaking changes in 1.0

The logged action of the output events is now an Enum instead of a string. The output event onChange does not exist anymore.

Install

$ npm install ng2-file-input --save

Import the module

// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { Ng2FileInputModule } from 'ng2-file-input'; // <-- import the module
import { MyComponent } from './my.component';

@NgModule({
    imports: [BrowserModule,
              Ng2FileInputModule.forRoot() // <-- include it in your app module
             ],
    declarations: [MyComponent],  
    bootstrap: [MyComponent]
})
export class MyAppModule {}

Import the styles

This library uses Bootstrap 4, so make sure to install that if you want the default styling to apply.

If you use Sass / Scss you can import the styles like so:

@import "{}/node_modules/ng2-file-input/ng2-file-input.scss";

otherwise just include the css file like this in your styles.css:

@import '~ng2-file-input/ng2-file-input.css';

Usage

Use it in your template

<ng2-file-input></ng2-file-input> 

Output events

General: onAction

    <ng2-file-input (onAction)="onAction($event)"></ng2-file-input> 

The on-action event will fire whenever an action to the file input happens, returning the following object:

    id: //the file input's id that emits the action (useful if you use the service and handle multiple file inputs, see below)
    currentFiles: //list of the current files
    action: //see Enum below
    file: //the file that caused the action

The emitted Action is an Enum:

    export enum Ng2FileInputAction{
        Removed=0,
        Added= 1,
        InvalidDenied = 2,
        CouldNotRemove = 3,
        CouldNotAdd = 4,
    }

You can use this Enum to check which action was emitted in your component like so (import it first of course):

    if(event.action===Ng2FileInputAction.Removed){
        //...
    }

Specific: onRemoved, onAdded, onInvalidDenied, onCouldNotRemove, onCouldNotAdd

    <ng2-file-input (onRemoved)="onRemoved($event)" (onInvalidDenied)="onInvalidDenied($event)"></ng2-file-input> 

Those actions fire when each correlating action happens, emitting the following object:

    id: //the file input's id that emits the action (useful if you use the service and handle multiple file inputs, see below)
    currentFiles: //list of the current files
    file: //the file that caused the action

Reset the file input or programatically add / remove files

Using the Ng2FileInputService you can easily reset the file input (removes all added files) or manually add and remove files. All you need to do so is to give the file input a UNIQUE identifier:

    <ng2-file-input [id]="myFileInputIdentifier"></ng2-file-input> 
    private myFileInputIdentifier:string = "tHiS_Id_IS_sPeeCiAL";
    constructor(private ng2FileInputService: Ng2FileInputService){

    }

    IResetBecauseICan():void{
        this.ng2FileInputService.reset(this.myFileInputIdentifier);
    }

Options

Available Options

Parameter Type Explanation
dropText string set the text for the dropzone
browseText string set the text for the browse button
removeText string set the text that appears when hovering over a preview element to remove
invalidFileText string set the text for the error that appears if an invalid file or with a disallowed extension was added
invalidFileTimeout number how long the error should appear, set to 0 if it should stay
multiple Boolean wether multiple files can be added or not
showPreviews Boolean show a preview of the selected file / files
accept string string for the input field accept attribute
removable Boolean should files be removable (through the preview)
extensions string[] the allowed extensions to be selected. Can either be ['image/jpeg', ...] or ['jpg',...]

Default global

You can set the options globally like so (below are the default values for the parameters if they are not set):

    Ng2FileInputModule.forRoot(
      {
         dropText:"Drop file here";
         browseText:"Browse";
         removeText:"Remove";
         invalidFileText:"You have picked an invalid or disallowed file."
         invalidFileTimeout:8000;
         removable:true;
         multiple:false;
         showPreviews:true;
         extensions:['jpg'];
      }
    ),

Per element

You can overwrite the default parameters per element:

<ng2-file-input [drop-text]="'my very custom dropzone text'"></ng2-file-input> 

Please note that instead of camelCase the lisp-case has to be used here.

Styling

All the elements have sepcific css classes, please just look them up using the element inspector.

To-do (Pull requests welcome)

  • Render preview for images better
  • Preserve EXIF orientation for the images preview
  • Add animations

ng2-file-input's People

Contributors

bergben avatar viccsjain avatar zivlevy 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

Watchers

 avatar  avatar  avatar  avatar

ng2-file-input's Issues

Angular 5: unmet peer dependancy @angular/core@^2.0.0

Hi,

Using the following Angular config:

Angular CLI: 1.6.8
Node: 6.11.3
OS: darwin x64
Angular: 5.2.5
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, platform-server, router

angular/cli: 1.6.8
angular-devkit/build-optimizer: 0.0.42
angular-devkit/core: 0.0.29
angular-devkit/schematics: 0.0.52
ngtools/json-schema: 1.1.0
ngtools/webpack: 1.9.8
schematics/angular: 0.1.17
typescript: 2.6.2
webpack: 3.10.0

I get the following NPM error:
[email protected] requires a peer of @angular/core@^2.0.0 but none was installed.

How can I satisfy this using @angular/[email protected]?

Many thanks.

fully qualified path in event

I'm not seeing the full path in the file-added event. Am I able to get to the file content once the file is selected, or the full path of the file selected?

noValidFileText not appear

when I choose any file no messages appear . Note that I didn't change the extensions . what I should do ?
thanks in advance :)

An example for input "accept" would be nice

I tried to use the input "accept" but I did not succeed.

<ng2-file-input [multiple]="false" [extensions]="['txt']" [show-previews]="true" [accept]="module.name+'.txt'"></ng2-file-input>

A little example in README file would be nice!

Rotating images after choosing

After choosing some jpegs (maybe other extensions too) image is rotated 90 degrees. Visible rotated image in preview.

add method in ng2FileInputService, on component init

Error when trying to add file through service in OnInit hook

ERROR TypeError: Cannot read property 'currentFiles' of undefined
at eval (file-input-handler.service.js:33)
at Array.forEach ()
at FileInputHandlerService.addFiles (file-input-handler.service.js:32)
at Ng2FileInputService.add (ng2-file-input.service.js:14)
...

[show-previews] value is not editable.

I've tried to hide the selected file previews since I'm only interested in directly showing the compressed image result. However, the previews are always visible. I think the issue lies in the code for file ng2-file-input.component.ts, line 52:

this.showPreviews = this.showPreviews || this.defaultOptions.showPreviews;

Since this is an OR comparison, if the default option is true, then no matter which is the input's value for [show-previews], the expression will always result true.

So far I've managed to hide it by overriding its CSS class:

.ng2-file-input-files   {
  display: none;
}

add default palceholder picture for non image types

hi

please add an ability to add a json file for non image file picture placeholder like .pdf.
for example:
<ng2-file-input (onAction)="fileChange($event)"
[typePlaceHolder]="{'.pdf':data:image/png;base64,iVBORw0KGg}"
extensions="['jpeg','png','jpg','pdf']">

then base64 image place on src img tag attribute and show that image and title beside each other.

regards

How to validate image size? (ex: less than 2MB)

public onAction(event: any) {
this.resImagesSize = event.currentFiles;
for (let i = 0; i < this.resImagesSize[i].size; i++) {
if (this.resImagesSize[i].size > 2000000) {
this.toasterService.pop('error', 'Error', 'Please upload less than 2MB image');
this.resImagesSize.splice(i, 1);
} else {
this.resImages = this.resImagesSize;
}
}
}

Is there any way to validate ?, because I tried to validate like this... but the problem is when i upload more than 2 images it display 2 popup messages..... any solution ??

Typo in readme for the specific event's names

Specific: OnRemoved, OnAdded, OnInvalidDenied, OnCouldNotRemove, OnCouldNotAdd

`<ng2-file-input (OnRemoved)="OnRemoved($event)" (OnInvalidDenied)="OnInvalidDenied($event)"></ng2-file-input> `

The "On" part should be lowercase: onAdded, onInvalidDenied, etc etc.
Not a big deal, I noticed while trying to understand why it wasn't working and seeing the onAction was using lowercase.

Please add a @NgModule (following migration to angular 5)

Hi,

I'm getting compiler.js:466 Uncaught Error: Unexpected value '[object Object]' imported by the module 'HubModule'. Please add a @NgModule annotation.

I migrated angular 4 to 5 today.
By checking with console.logs / breakpoints, I was able to identify the fact that ng2FileInputModule was responsible for it. Could not understand why since you declare @NgModule properly in your file.

Trace :
Uncaught Error: Unexpected value '[object Object]' imported by the module 'HubModule'. Please add a @NgModule annotation. at syntaxError (compiler.js:466) at compiler.js:15088 at Array.forEach (<anonymous>) at CompileMetadataResolver.webpackJsonp.../../../compiler/esm5/compiler.js.CompileMetadataResolver.getNgModuleMetadata (compiler.js:15071) at CompileMetadataResolver.webpackJsonp.../../../compiler/esm5/compiler.js.CompileMetadataResolver.getNgModuleSummary (compiler.js:14998) at compiler.js:15086 at Array.forEach (<anonymous>) at CompileMetadataResolver.webpackJsonp.../../../compiler/esm5/compiler.js.CompileMetadataResolver.getNgModuleMetadata (compiler.js:15071) at CompileMetadataResolver.webpackJsonp.../../../compiler/esm5/compiler.js.CompileMetadataResolver.getNgModuleSummary (compiler.js:14998) at compiler.js:15086

OnChange, objects are empty

First of all, awesome package and thanks for putting it out there. I installed the package and tested it in the html and the previews work fine and also setting multiple to true or false. However, when I console log the event with (onChange)="method($event)"

This is what I get:

{
    "currentFiles": [
        {}
    ],
    "action": "added",
    "file": {}
} {}

As you can see, everything is empty.

This is my app.module.ts file

import { Ng2FileInputModule } from 'ng2-file-input';
imports: [Ng2FileInputModule.forRoot()]

My component html file:
<ng2-file-input (onChange)="fileChange($event)" placeholder="Profile Picture" [drop-text]="'my very custom dropzone text'" [multiple]="false"></ng2-file-input>

My component.ts file:

fileChange(event: any){
    console.log(`This is file ${JSON.stringify(event, null, 4)} ${JSON.stringify(event.file, null, 4)}`);
}

I searched for the files in node_module folder and i was able to see.

Ng2FileInputComponent.prototype.handleFile = function (file) {
        if (this.isValidFile(file)) {
            if (!this.multiple) {
                this.currentFiles = [];
            }
            this.currentFiles.push(file);
            console.log('This is current file ', this.currentFiles, ' and this is file ', file);
            this.output.emit({
                currentFiles: this.currentFiles,
                action: "added",
                file: file
            });
        }
    };

I changed the file:file to file:"hi" and that displayed in my fileChange($event) method in the component.ts file. Also, as you can see from above, I also have a console log that I put:

console.log('This is current file ', this.currentFiles, ' and this is file ', file);
which prints:

lastModified: 1476747913000
lastModifiedDate: Mon Oct 17 2016 19:45:13 GMT-0400 (EDT)
name:"f6fdde3a-056a-4d08-bf53-a6c9aa289d28.png"
size:5272
type:"image/png"
webkitRelativePath:""

Now I really don't know why the object files are empty in the fileChange() method, maybe there is some sort of delay that I need to be looking for? I am using ng2-bootstrap and also have bootstrap cdn css. Please can you help with this?

Show file content in text area

Hi it is not an issue i m havin a struggle
I am trying to load a file using ng2-file-input using following line :
<ng2-file-input (onChange)="onFileChange($event)"></ng2-file-input> and in the component i am using :

public onFileChange(event: any)
   {
 console.log("the file has changed:", event);   
 console.log('This is file' + JSON.stringify(event, null, 4)+JSON.stringify(event.file, null, 4));
    }

I want to know if there is any way to get the file content so i can show it in text area

Double input visible

Hello

I don't understand but I have a double input (one with bootstrap style) and one with crappy style.

Version: 1.1.0

My code:

<div class="company-image">
         <img src="assets/images/profilePicture.png" *ngIf="!company.pictures || !company.pictures.originial"/>
         <div class="file-chooser">
           <ng2-file-input (OnRemoved)="OnRemoved($event)" (OnInvalidDenied)="OnInvalidDenied($event)" [drop-text]="'Glisser un fichier ici'"></ng2-file-input>
         </div>
       </div>

Generated code:

<ng2-file-input _ngcontent-c2="" ng-reflect-drop-text="Glisser un fichier ici"><div class="ng2-file-input">
                    <div class="ng2-file-input-invalid text-danger" hidden="">Mauvais choix</div>
                    <div class="ng2-file-input-drop-container" filedrop="" ng-reflect-klass="ng2-file-input-drop-container" ng-reflect-ng-class="[object Object]">
                        <span>Glisser un fichier ici</span>
                        <button class="btn btn-primary" type="button">Choisir</button>
                    </div>
                    <!--bindings={
  "ng-reflect-ng-if": "false"
}-->
                    <input type="file" accept="undefined">
                </div></ng2-file-input>

Render is file attached:

untitled

Angular 4+

Getting the following warnings

npm WARN [email protected] requires a peer of @angular/core@^2.0.0 but none was installed.
npm WARN [email protected] requires a peer of @angular/platform-browser@^2.0.0 but none was installed.
npm WARN [email protected] requires a peer of @angular/common@^2.0.0 but none was installed.
npm WARN [email protected] requires a peer of @angular/core@^2.0.0 but none was installed.

using

@angular/cli: 1.3.1
node: 8.6.0
os: darwin x64
@angular/animations: 4.3.5
@angular/cdk: 2.0.0-beta.8
@angular/common: 4.3.5
@angular/compiler: 4.3.5
@angular/core: 4.3.5
@angular/forms: 4.3.5
@angular/http: 4.3.5
@angular/language-service: 4.3.5
@angular/material: 2.0.0-beta.8
@angular/platform-browser: 4.3.5
@angular/platform-browser-dynamic: 4.3.5
@angular/router: 4.3.5
@angular/cli: 1.3.1
@angular/compiler-cli: 4.3.5

Angular 2 project with angular-cli -Browse button not firing

Hello,
i'm trying to use ng2-file-input in my angular 2 project.
I have problems with the "Browse" button, when i click it, no file selector widow is shown.
The "Drop" functionality works fine.

In the Chrome console i see this error:
dist/FileAPI.flash.swf?r=2.0.21 404 not Found.

I read your solution setting the "paths" in tsconfig.json, i do it, but it doesn't work.

--Update:
I understand that it's a angular 2 problem, so it is not related to ng2-file-input.

Thanks

How to access selected file to upload it on server

event.currentFiles[i]
returns me file object as
File { name: "Tanmay Surlekar.JPG", lastModified: 1505560052000, lastModifiedDate: Date 2017-09-16T11:07:32.000Z, webkitRelativePath: "", size: 51264, type: "image/jpeg" }

Now, I want to upload this file one by one to server, or may be the array of files as it is. But, this wont help as on server end I'm just getting blank objects same as the size of currentFiles array. That is, if I select 5 files on client side then I get 5 blank object's array on server.

error loading css

Hello,

I'm getting an error when loading the css.

GET http://localhost:4200/node_modules/ng2-file-input/ng2-file-input.css net::ERR_ABORTED

I have done the npm install of your package, added it to my app-module and included the script tag of the css to my index.html (in the head section)

My app is still running though but what I've noticed so far is that when I remove a previewed image it also closes the modal in which I am using the ng2-file-input selector. Not sure if this has something to do with the css not loading or with something else. Any idea what could be causing this and how to fix it?
I'm also seing 2 buttons to selext files (one larger button "browse" and one smaller "choose files")
I guess the second is the standard input type="file" button and this one would be hidden if the css would load?

Kind regards

Metadata Mismatch version

ERROR:
ERROR in Metadata version mismatch for module /home/projects/front-end/node_modules/ng2-file-input/dist/ng2-file-input.d.ts, found version 4, expected 3, resolving symbol GeneralModule in /home/projects/Finch/front-end/src/app/modules/shared/general.module.ts, resolving symbol GeneralModule in /home/projects/Finch/front-end/src/app/modules/shared/general.module.ts, resolving symbol GeneralModule in /home/projects/Finch/front-end/src/app/modules/shared/general.module.ts

my package.json

{
"name": "testapp",
"version": "0.0.0",
"license": "MIT",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"angular/animations": "^4.0.0",
"angular/cdk": "^2.0.0-beta.12",
"angular/common": "^4.0.0",
"angular/compiler": "^4.0.0",
"angular/compiler-cli": "^4.0.0",
"angular/core": "^4.0.0",
"angular/forms": "^4.0.0",
"angular/http": "^4.0.0",
"angular/material": "^2.0.0-beta.12",
"angular/platform-browser": "^4.0.0",
"angular/platform-browser-dynamic": "^4.0.0",
"angular/platform-server": "^4.0.0",
"angular/router": "^4.0.0",
"bootstrap": "^3.3.7",
"core-js": "^2.4.1",
"easy-pie-chart": "^2.1.7",
"materialize-css": "^0.100.2",
"ng2-file-input": "^1.1.4",
"rxjs": "^5.2.0",
"zone.js": "^0.8.5"
},
"devDependencies": {
"angular/cli": "1.0.0",
"types/jasmine": "2.5.38",
"types/node": "~6.0.60",
"codelyzer": "~2.0.0",
"jasmine-core": "~2.5.2",
"jasmine-spec-reporter": "~3.2.0",
"karma": "~1.4.1",
"karma-chrome-launcher": "~2.0.0",
"karma-cli": "~1.0.1",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"karma-coverage-istanbul-reporter": "^0.2.0",
"protractor": "~5.1.0",
"ts-node": "~2.0.0",
"tslint": "~4.4.2",
"typescript": "~2.4.0"
}
}

when i commented Ng2FileInputModule imports from general module and then again uncomment it and type the command ng-serve it will work fine and again stop and again compile it shows error...

Prevent the users from adding new files through attribute

After the users selected n files I enable an upload button.

While I can manage to disable the removal of selected files, I cannot stop the users from adding new files.
As a workaround i'm hiding the drop area but I'd like to see a nicer UI response like a greyed out area and disabled button.

Not compatible with Angular 5.0

ERROR in node_modules/ng2-file-input/dist/src/ng2-file-input.module.d.ts(1,31): error TS2305: Module
... /node_modules/@angular/core/core"' has no exported member 'OpaqueToken'.

OpaqueToken was deprecated in angular 4 and removed in angular 5
Replaced with InjectionToken

Browser module already imported

Importing the module into a lazy loaded module is impossible..

BrowserModule has already been loaded. If you need access to common directives such as NgIf and NgFor from a lazy loaded module, import CommonModule instead.

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.