9

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]
            );
            });
2
  • 1
    Add the relevant code to your question. Commented Aug 3, 2017 at 16:56
  • File is still missing on console? Can you inspect the request in network tab? Commented Aug 4, 2017 at 9:55

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.