File Upload in Angular 4

Viewed 48610

when I'm trying to install "npm install ng2-file-upload --save" in my angular 4 application it throws

UNMET PEER DEPENDENCY @4.1.0
UNMET PEER DEPENDENCY @4.1.0
`-- ng2-file-upload@1.2.1

and upload is not working my applications throws

"Can't bind to 'uploader' since it isn't a known property of 'input'"

this is my HTML

<input type="file" ng2FileSelect [uploader]="upload" multiple formControlName="file" id="file"/>

and its Component

import { FileUploadModule } from 'ng2-file-upload/ng2-file-upload';   
import { FileSelectDirective, FileUploader } from 'ng2-file-upload/ng2-file-
upload';

export class PersonalInfoComponent implements OnInit
{
    public upload:FileUploader= new FileUploader({url:""});
}

Parent Module

import { FileUploadModule } from 'ng2-file-upload/ng2-file-upload';

@NgModule({

imports: [
..
....
..
FileUploadModule
],

export class RegistrationModule { }

and I didn't Import/change anything in AppModule(Grand Parent Module).

can someone help me on this please...

6 Answers

I don't think we need some extra libraries

onFileChange(event){
   let files = event.target.files; 
   this.saveFiles(files);
    }
@HostListener('dragover', ['$event']) onDragOver(event) {
    this.dragAreaClass = "droparea";
    event.preventDefault();
}
@HostListener('dragenter', ['$event']) onDragEnter(event) {
    this.dragAreaClass = "droparea";
    event.preventDefault();
}
@HostListener('dragend', ['$event']) onDragEnd(event) {
    this.dragAreaClass = "dragarea";
    event.preventDefault();
}
@HostListener('dragleave', ['$event']) onDragLeave(event) {
    this.dragAreaClass = "dragarea";
    event.preventDefault();
}
@HostListener('drop', ['$event']) onDrop(event) {   
    this.dragAreaClass = "dragarea";           
    event.preventDefault();
    event.stopPropagation();
    var files = event.dataTransfer.files;
    this.saveFiles(files);
}

And now we are ready to upload files with drag and drop as well as by clicking the link button and upload extra data with files.

See the complete article here Angular 4 upload files with data and web api by drag & drop

You don't need an external library to do this, check below sample code

@Component({
    selector: 'app-root',
    template: '<div>'
        + '<input type="file" (change)="upload($event)">'
        + '</div>',
})

export class AppComponent {

    constructor(private _service: commonService) { }

    upload(event: any) {
        let files = event.target.files;
        let fData: FormData = new FormData;

        for (var i = 0; i < files.length; i++) {
            fData.append("file[]", files[i]);
        }
        var _data = {
            filename: 'Sample File',
            id: '0001'
        }

        fData.append("data", JSON.stringify(_data));

        this._service.uploadFile(fData).subscribe(
            response => this.handleResponse(response),
            error => this.handleError(error)
        )
    }
    handleResponse(response: any) {
        console.log(response);
    }
    handleError(error: string) {
        console.log(error);
    }
}

More info

import fileupload from primeng or use simple file uploader

HTML

  <p-fileUpload name="myfile[]"  customUpload="true" 
     (uploadHandler)="uploadSuiteForRelease($event)" auto="auto"></p-fileUpload> 

TS

 var data = new FormData();
        let index: number = 0;
        if (this.files != undefined)
        {
            for (let file of this.files.files)
            {
                data.append("myFile" + index, file);
                ++index;
            }
        }
     data.append('viewModel', JSON.stringify(<<data model that needs to be 
     sent with request>>));

Send this data with request return this._httpClient.post('api/controller', data);

Server

  [HttpPost]
        public async Task<IHttpActionResult> Post()
        {
            HttpPostedFile httpPostedFile = null;
            var viewModel = JsonConvert.DeserializeObject<ReleasesViewModel>(HttpContext.Current.Request["viewModel"]);
            if (viewModel != null)
            {
                if (HttpContext.Current.Request.Files.AllKeys.Any())
                {
                    var cnt = HttpContext.Current.Request.Files.Count;
                    for (int i = 0; i < cnt; i++)
                    {
                        httpPostedFile = HttpContext.Current.Request.Files["myFile" + i];
                    }
                }
            }
        }
Related