1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

  2. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

Angular 2 - How to upload file and store in local folder

Discussão em 'Angular' iniciado por weikian, Dezembro 14, 2024.

  1. weikian

    weikian Guest

    For example, I created a folder called 'upload' under src folder.

    html file:

    <div>
    <input type="file" id="photo" (change)="onChange($event)" />
    </div>
    <div class="col-md-6 mb-4 mt-3">
    <button (click)="upload()" class="btn btn-primary w-100">Upload Picture</button>
    </div>


    upload-modal.component.ts file

    import { Http, Response } from '@angular/http';
    import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
    import "rxjs/add/operator/do";
    import "rxjs/add/operator/map";
    const uploadURL = '/upload';

    @Component({

    selector: 'upload-modal',
    templateUrl: './upload-modal.component.html',
    styleUrls: ['./upload-modal.component.css']
    })
    export class UploadModalComponent {
    displayMessage: string = '';
    constructor(public activeModal: NgbActiveModal, private http: Http, private el: ElementRef) { }
    setDisplayMessage(msg: string) {
    this.displayMessage = msg;
    }

    upload() {
    this.activeModal.dismiss('Cross click');
    }

    onChange(event) {
    let inputEl: HTMLInputElement = this.el.nativeElement.querySelector('#photo');

    let fileCount: number = inputEl.files.length;

    let formData = new FormData();

    if (fileCount > 0) { // a file was selected

    formData.append('photo', inputEl.files.item(0));

    this.http
    .post(uploadURL, formData).map((res: Response) => res.json()).subscribe(
    // map the success function and alert the response
    (success) => {
    alert("success");
    },
    (error) => alert("error"));
    }

    }
    }


    when I click upload button, and I found this error in console log= http://localhost:3000/upload 404 (Not Found)
    I guess this must to do with routing. Anyone has experience before?

    Continue reading...

Compartilhe esta Página