-1

How upload image with Angular 4 ?

<input type="file" (change)="uplod($event)"/>

Spring code :

@RequestMapping(value="/Etablissement/upload", method=RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<Object> uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
    File convertFile = new File("C:/Users/acer/reservationF/reservation/reservation/image"+file.getOriginalFilename());
    convertFile.createNewFile();
    FileOutputStream fout = new FileOutputStream(convertFile);
    fout.write(file.getBytes());
    fout.close();
    return new ResponseEntity<>("File is uploaded successfully", HttpStatus.OK);
}
Ram
  • 1,743
  • 2
  • 18
  • 40
  • Possible duplicate of [File Upload in Angular 4](https://stackoverflow.com/questions/43993145/file-upload-in-angular-4) – Striped Feb 22 '18 at 23:24
  • Refer my answer from this link https://stackoverflow.com/questions/48279484/sending-file-object-to-spring-rest-controller-through-angular-5/48295301#48295301 – hrdkisback Mar 05 '18 at 09:54

2 Answers2

0

Try this code. This worked for me. You don't have to import any external libraries for this method.

<input type="file" (change)="fileChange($event)" placeholder="Upload file" accept=".pdf,.doc,.docx">

fileChange(event) {
    let fileList: FileList = event.target.files;
    if(fileList.length > 0) {
        let file: File = fileList[0];
        let formData:FormData = new FormData();
        formData.append('uploadFile', file, file.name);
        let headers = new Headers();
        /** No need to include Content-Type in Angular 4 */
        headers.append('Content-Type', 'multipart/form-data');
        headers.append('Accept', 'application/json');
        let options = new RequestOptions({ headers: headers });
        this.http.post(`${this.apiEndPoint}`, formData, options)
            .map(res => res.json())
            .catch(error => Observable.throw(error))
            .subscribe(
                data => console.log('success'),
                error => console.log(error)
            )
    }
}
Ishara Sandun
  • 699
  • 1
  • 7
  • 13
0

I found the solution with some modification Angular 4 – Upload/Get MultipartFile to/from Spring Boot Server