Code Monkey home page Code Monkey logo

ngx-input-file's Introduction

ngx-input-file

ngx-input-file is a module to replace the html element input file with Material Design.

Try it with Stackblitz!

For the previous version with bootstrap: [email protected].

Key features

  • Preview of the file
  • Drag and drop zone
  • Responsive

Installation

npm install ngx-input-file --save

Basic Configuration

import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { InputFileConfig, InputFileModule } from 'ngx-input-file';

const config: InputFileConfig = {};

@NgModule({
    imports: [
        ...
        BrowserAnimationsModule,
        InputFileModule.forRoot(config),
        ...
    ],
    ...
})

export class MyModule {}

Please include material-design-icons in your angular.json:

"styles": [
    "node_modules/material-design-icons/iconfont/material-icons.css",
    "src/styles.scss"
]

Component Attributes

These settings will overide the configuration defined with forRoot() method.

Attribute Type Description
fileAccept Input - string The attribute accept of the html element input.
fileLimit Input - number The maximum files that the user can upload.
iconAdd Input - string The icon for add.
iconDelete Input - string The icon for delete.
iconFile Input - string The icon for file.
iconLink Input - string The icon for link.
linkEnabled Input - boolean Whether adding is url is enabled.
placeholderLink Input - string The placeholder for the link input.
sizeLimit Input - number The maximum size of the file (kB).
disabled Input - boolean Whether the component is disabled.
placeholder Input - string The placeholder of the component.
classAnimation Input - string The class of the image container which allow to animate the container when select or drop a file.
ngModel/formControlname Array Template driven or reactive form works.
acceptedFile Output - InputFile Triggered when a file is accepted.
deletedFile Output - InputFile Triggered when a file is deleted.
rejectedFile Output - InputFile Triggered when a file is rejected.

Configuration Attributes

Attribute Type Default Description
classAnimation string 'bounce-in' The class of the image container which allow to animate the container when select or drop a file.
fileAccept string '*' The attribute accept of the html element input.
fileLimit number 1 The maximum files that the user can upload.
iconAdd string 'add' The icon for add.
iconDelete string 'delete' The icon for add.
iconFile string 'insert_drive_file' The icon for file.
iconLink string 'link' The icon for link.
linkEnabled boolean false Whether adding is url is enabled.
placeholderLink string 'Link' The placeholder for the link input.
sizeLimit number null The maximum size of the file (kB).

Example

<input-file
    placeholder="My files"
    [(ngModel)]="myModel">
</input-file>

<input-file
    placeholder="Pictures"
    formControlName="myField">
</input-file> 

Bonus

Here's an example to post a file:

import { HttpClient } from '@angular/common/http';

@Injectable()
export class MyRepository {

constructor(
    private http: HttpClient
) {}

public post(file: InputFile): Observable<YourClass> {
    const apiUrl = 'my-url';
    const formData = new FormData();
    formData.append('file', file.file, file.file.name);
    return this.http.post<YourClass>(apiUrl, formData).pipe(
        .catchError(...)
}

For developpers

You're welcome, please fork this repository to a make pull request.

Demonstration

Clone this repository and run npm start.

ngx-input-file's People

Contributors

lerenzom avatar msivade avatar padjon avatar rsaenen avatar slimentn 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

ngx-input-file's Issues

How to get the file blob

How do i get the file's blob once i submit the form?
I have a form with a few fields, and used console log on the submitted form.

image

As you can see, at the "form.value.pdf" there are the files, however it has no "file" attribute like shown in the example
(const formData = new FormData();
formData.append('file', file.file, file.file.name);
And there are a few meta-data but no blob content for me. How do i get that?

My relevant html look like this:
image

ngx-input-file sizeLimit no funciona

Estoy implementando el ngx-input-file en mi aplicacion angular, sin embargo aunque le pongo un tamaño maximo al archivo sizeLimit="50", si intento subir un archivo de 100kb me lo procesa sin verificar el tamaño maximo. Incluso si se hacemos la prueba en https://stackblitz.com/edit/ngx-input-file tambien tiene el mismo comportamiento. Este es el ejemplo que estaba intentando

<input-file placeholder="Drop files below!" fileLimit="1" sizeLimit="50"></input-file> pero el sizeLimit no tiene ningun efecto. Agradezco cualquier indicacion.

ngx-input-file Angular 10 issue

IMPORTANT:
Currently not compatible with angular 10 update

Steps to reproduce and a minimal demo

- ng update @angular ng update @angular/cli_
- _Stackblitz example Appreciated_

Current behavior
Generic type 'ModuleWithProviders' requires 1 type argument(s).

4 static forRoot(config: InputFileConfig): ModuleWithProviders;
-

Expected/desired behavior
Support for angular 10

Overwrite form control InputFile on custom data.

I have form group consist with some text input and one ngx-input-file (named image).
I'm selecting my image and then immediately upload to server. My service return URL to uploaded image.

My goal is overwrite image form control with returned URL. Like this:

<input-file
    formControlName="image"
    (acceptedFile)="acceptedImage($event)">
</input-file>


    public acceptedImage(file: InputFile): void {
        this.service.uploadImage(file)
            .subscribe(
                data => {
                    this.form.value.image = data.url;
                });
    }

All works properly! But when I edit any other form control i lost my overwritten data.
My image from control again is InputFile object. Any solution?

Switch BrowserModule Dependency to Common Module

Hey,

I love your component but I had a problem integrating it into my application when using the angular router. This component imports the Browser Module component which breaks on Angular if something else imports it. I tried it out with the Common module and it works perfectly fine. Could you switch to using the Common Module instead so there is easier integration?

Thanks!

Problem with file sizes

Hi,

I have an issue when I try to load a big image (>15 MB), it thows an error by console (RangeError: Maximum call stack size exceeded) and freeze the app.

Steps to reproduce

- Select an +15 MB image 

Current behavior

- 

image

Expected/desired behavior

- It should not freeze an handle the exception.

Environment information

- OS: Windows 10
- Angular Version: cli 6.2.5 
- Typescript version: 7
- npm version: 6.4.1
- Node Version: 10.13.0

Other information
The images I'm been trying were JPG

ChangeDetectionStrategy.OnPush

IMPORTANT:
Please be specific with an example. An issue with

Steps to reproduce and a minimal demo

  1. Set changeDetection value for Component decorator to "ChangeDetectionStrategy.OnPush"
  2. Try to select some file\files
  3. Now selected files values not in ngModel or FormControl
  4. Click outside from InputFile control ot click on add icon
  5. Now selected files values pass to ngModel or FormControl

Current behavior

-  Demo on StackBlitz https://stackblitz.com/edit/ngx-input-file-ykj3ux

Expected/desired behavior

- 

Environment information

- OS: 
- Angular Version: 
- Typescript version:
- npm version: 
- Node Version: 

Other information

Discussion: future of the package

Hello,
I created this package with Angular 2 and Bootstrap and it evolves a bit with material guidelines.

I learned a lot and I has more free time than now. However, my lack of motivation is incompatible to close all issues and to handle this package.

I would be thankfull to people who can fork and support this package.

How can I trigger validation on drag drop files

IMPORTANT:
Please be specific with an example. An issue with While trying to drop files im trying to call a function which does validation on the dropped file.
Currently I'm not able to call a function while dropping files.
Can you please help me on it.

how to use (change) to send a file to other library

Hi how are you? Im using your library to limit the size of images in my project, and using ngx-image-cropper to cut my image, the problem is image use (change) on input type file to send $event to library, can you tell me how to use (change) and send file or $event to this library?

Disconnection of the Model

After deleting all the files I go back to find other files but I no longer upload them to the model. The tests I'm doing with the files of this repo.

Stackblitz example not working

Stackblitz example is in endless loading state. There are some problems with fetching material design icons dependency. Tested on Firefox 62.0.2 and Chrome Version 69.0.3497.100. Windows 10 64bit.

Has no exported member 'InputFileConfig'.

IMPORTANT:
Please be specific with an example. An issue with
I used the same code as in demo, but I always got node_modules/ngx-input-file/ngx-input-file has no exported member 'InputFileConfig' error.

Environment information

- OS: Mac
- Angular Version: 5.2.0
- Typescript version: ~2.5.3
- npm version: 6.1.0
- Node Version: 8.11.3

Other information

Drag/Drop does not work with Safari

Steps to reproduce and a minimal demo

- Open Safari here: https://ngx-input-file.stackblitz.io/

Current behavior

-  Drag and Drop does not work with Safari
-  Stackblitz demo does not load with Safari
-  It works to click and upload a file on my app via Safari but NOT drag/drop

Expected/desired behavior

- Safari is supported without errors

Environment information

- OS: macOS Mojave 10.14.6
- Browser: Safari 12.1.2
- Angular Version: ^7.2.0
- Typescript version: ^3.2.4
- npm version: 6.9.0
- Node Version: 10.16.0
- ngx-input-file version: ^7.0.1

Other information

-  ReferenceError: Can't find variable: DragEvent

probleme with displaying images, after deleting one

IMPORTANT:
Please be specific with an example. An issue with

Steps to reproduce and a minimal demo

  • i'm using rest back end to get images
  • preload inputFilelComponent with the images like :
    ...
    @ViewChild(InputFileComponent)
    ...
    this.InputFileComponent.files.push({link: url, file: new File([url], name, {type: imageType} ), preview: url});

Current behavior

- first the images are well displayed
- once i click delete icon on any image, the image is deleted but the remainning images are not displayed correctly

Expected/desired behavior

- 

Environment information

Angular CLI: 6.0.8
Node: 9.0.0
OS: darwin x64
Angular: 6.1.10
bootstrap 4

Other information

iconAdd not working when using fontawesome icon.

IMPORTANT:
Please be specific with an example. An issue with

Using the iconAdd configuration and component attribute field. When I use my downloaded icon in 'iconAdd', the icon is not rendered. Is there support for anything other than mat-icons?

Expected/desired behavior

To be able to use a fontawesome icon rather than a the default add icon.

Hide file preview div

Hello,

I am sorry to ask for this because I'm sure you have put a lot of effort into the preview-div and it does look beautiful. However, for my project, I really only need the input fields, without the preview-div.

Is this possible? I know using [minimal]=true within the input-file div is still possible, but this hides way too much.

Thank you

Hide/remove all the buttons

All we need is the upload-box, we don't need the upload/remove/select-buttons. Is it possible, or would it be easy to implement a way to not show them?

How to override style and icon?

ngx-input-file version: 2.0.2
Angular: 6.0.6
Angular Material: 6.3.0

Current behavior

- <mat-icon>add</mat-icon> is used by default
- No simple way to override .file-button style.

Expected/desired behavior

- Allow to change to any other material icons.
- Override .file-button css style

Is it possible to have a request on each action?

Greetings, very useful your library, im implementing on a project.

IMPORTANT:
i have this requirement, to send the http request on each selection, change and also on delete (of course when deleting, i need to send an identifier.

I've selected an image, then should send the http request to upload the file.
i've changed an uploaded image, so i need to send the http request to let them know i have changed.
i've deleted an uploaded image, so i need to send the http request to let them know i have deleted specific image.

- OS:  Windows 10
- Angular Version: 13

Is it possible to have this kind of functionalities with this library?

Error Remove All

I click on the Remove button and when I read the length property of the model it remains the same as when I select the files

ngx-input-file with reactive forms

Hi,

Can you provide an example demonstrating how to use input-file directive with reactive forms?

I tried to create a form group

this.form = this._fb.group({
    ...
    images: this._fb.array([this._fb.control(this.product.image[0], Validators.required)])
});

And setup input-file like this

<form name="form" [formGroup]="form">
    ...
    <input-file
        formControlName="images"
        placeholder="Images"
        fileLimit="1"
        fileAccept="image/png">
    </input-file>
</form>

But I'm getting the following error

TypeError: control.registerOnChange is not a function

What am I doing wrong?

Thanks in advance

Diogo

Has a way to increase the preview image size?

As I see the preview show the image in 160pixels x 160pixels.

Has a way to increase the preview image size? But only for one "file input"
LIke to 320pixels x 320pixels or higher...

Thanks xD

Error in: [ngClass]="{'input-active': isInputActive}"

This error appears when using your directive, after browsing and selecting a file:

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'true'. Current value: 'false'.

screen shot 2017-12-07 at 3 53 47 pm
screen shot 2017-12-07 at 3 52 44 pm

Unable to show existing image with url

Here is my code:

pageImageList: PageImages[] = [];
  pageImagesForm: FormGroup;
  constructor(public authService: AuthService,
              private formBuilder: FormBuilder,
              public initializationService: InitializationService,
              private cdr: ChangeDetectorRef) {

               }

  ngOnInit() {
    this.pageImagesForm = this.formBuilder.group({
      mainPagePicture: ['', [FileValidatorDirective.validate]],
      productPagePicture: ['', [FileValidatorDirective.validate]],
      projectPagePicture: ['', [FileValidatorDirective.validate]],
      brandPagePicture: ['', [FileValidatorDirective.validate]],
      blogPagePicture: ['', [FileValidatorDirective.validate]]
    });
  }
  ngAfterViewInit() {
    this.pageImagesForm.get('mainPagePicture')
            .setValue(this.tabChanged(0));
            this.cdr.detectChanges();
  }

  onTabChanged(event) {
          if (event.index === 0) {
            this.pageImagesForm.get('mainPagePicture')
            .setValue(this.tabChanged(event.index + 1));
          } else if (event.index === 1) {
            this.pageImagesForm.get('productPagePicture')
            .setValue(this.tabChanged(event.index + 1));
          } else if (event.index === 2) {
            this.pageImagesForm.get('projectPagePicture')
            .setValue(this.tabChanged(event.index + 1));
          } else if (event.index === 3) {
            this.pageImagesForm.get('brandPagePicture')
            .setValue(this.tabChanged(event.index + 1));
          } else if (event.index === 4) {
            this.pageImagesForm.get('mainPagePicture')
            .setValue(this.tabChanged(event.index + 1));
          }
  }
tabChanged(index): InputFile[] {
    const retrievedImages = new Array<InputFile>();
    this.initializationService.getPageImages(index + 1).subscribe(images => {
        images.map( (x, i) => {
        this.toDataURL(`assets/pages/${x.pageId}_${x.imageId}.${x.fileExtension.split('/')[1]}`, (dataUrl) => {
          const inputFile: InputFile = { id: i + 1,
            preview: dataUrl,
            file: new File([dataUrl], `${x.pageId}_${x.imageId}`, {
            type: dataUrl.split(';')[0].split(':')[1]
          })};
          retrievedImages.push(inputFile);
          });
      });
      this.pageImageList = this.pageImageList.filter(y => y.pageId !== index + 1);
      this.pageImageList = [...images];
      });
      return retrievedImages;
  }

  toDataURL(url, callback) {
    const xhr = new XMLHttpRequest();
    xhr.onload = () => {
        const reader = new FileReader();
        reader.onloadend = () => {
            callback(reader.result);
        };
        reader.readAsDataURL(xhr.response);
    };
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.send();
}

when I retrieve the images from the urls everything is OK but when I select one of the images to change, the other image is gone!!!!
image

is there any approach to show and change existing files or images?

Preview of uploaded image in edit component.

Uploading works perfectly. I accept only and only one image.
When I select my image from disk or paste url then i se preview. It works perfectly too.

But in my component to Edit I need to show preview of image. My service return model with URL to previously uploaded image.

How to show preview of image in input-file component? It is possible?

This is my form:

        return this.formBuilder.group({
            .....
            icon: new FormControl([])
        });

This is my template:

                <input-file
                        [formControlName]="'icon'"
                        linkEnabled="true">
                </input-file>

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.