Agular2 + typescript + file download

I am creating an angular2 project in which my requirement is to upload a file and send some parameters from the client to the server (Spring Rest Server). I tried the Formdata interface, but when I add a file to it (File Object created from event.srcElement.files) and then register an object for the console, it prints an empty formdata object. As for the back end, I use @requestparam ("file") to extract the file. It would be great if anyone could help with this.

this is the code in my html file

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

the component file is similar to 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 the 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] ); }); 
+5
source share
1 answer

Your HTML should be:

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

So, you will get the file in the 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) } 

You will then receive a file with the file key in the request data.

+4
source

Source: https://habr.com/ru/post/1270549/


All Articles