Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Agular2 + typescript + file upload

I am creating an angular2 project, in which my requirement is to upload a file and send some parameters from client to server(Spring Rest Server). I have tried Formdata Interface, but when i am appending a file(File Object created from event.srcElement.files) to it and then logging the object to console it prints an empty formdata object. As for the server side i am using @requestparam("file") to fetch the file. It would be great if anyone can provide some help on this.

this is the code in my html file

<input type="file" #uploadFile multiple="true" (change)="uploadFile($event)"/>

component file is like this

  uploadFile(event:any){
    let file = event.target.files[0];
    let fileName = file.name;
    console.log(file)
    console.log(fileName)
    let formData = new FormData();
    formData.append('file',file);
    this.examService.uploadAnswer(formData);
}

and in service file

uploadAnswer(formData:FormData){  
            console.log(formData)
            this.http.post(this.url+'/uploadanswer', formData)
            .map((response: Response) => {
                let res = response.json();
            Object.keys(res).forEach(name =>
                this.questions=res[name]
            );
            });
like image 323
parikshitcs0072 Avatar asked Aug 03 '17 16:08

parikshitcs0072


1 Answers

Your HTML should be:

<input id="file-field" name="file-field" (change)="uploadFile($event)" type="file" accept=".png,.jpg,.jpeg">

So you will get file in component as:

uploadFile(event) {
  let files = event.target.files;
  if (files.length > 0) {
    console.log(file); // You will see the file
    this.service.uploadFile(file);
  }
}

And in service:

uploadFile(file) {
  let formData: FormData = new FormData();
  formData.append('file', file, file.name);

  this.http.post(url, formData, request_options)
}

Then you will get file in with file key in request data.

like image 112
Malik Shahzad Avatar answered Nov 15 '22 21:11

Malik Shahzad