idan ovadia
idan ovadia

Reputation: 239

Send a File (an image) from Angular 8 to Spring Boot App

I want to send a file from my angular 8 app to my spring boot server

I tried in Spring - MultiPartFile ,HttpServletRequest and some more methods with no success.

I hope someone can tell me how to get the file in spring... and if need some changes in my angular app.

Angular 8

<input ngModel type="file" name="file" (change)="fileChange($event)" class="form-control-file" id="exampleInputFile" aria-describedby="fileHelp" required>
fileChange(event) {
    this.imageMentor = event.target.files[0];
  }

when I send the file - in the componnent

onFormSubmitMentor() {

    const dataImage = new FormData();
    dataImage.append('myFile', this.imageMentor, this.imageMentor.name);
    this.useDetailsService.addMentor(dataImage).subscribe(data => {
      }, Error => {
        if (Error.error.error === 'Unauthorized') {
          alert('Unauthorized');
        }
      });
  }

service

addMentor(dataImage) {
    const token = JSON.parse(localStorage.getItem('currentUser'));
    let headers = new HttpHeaders();
    headers = headers.append('Authorization', 'Bearer ' + token.token);
    headers = headers.append('Content-type', 'application/json');
    console.log(dataImage);
    return this.http
      .post(
        'http://localhost:8080/register/mentor',{file: dataImage}, {headers, responseType: 'text'}
      ).pipe(map((response: any) => {
        console.log(response);
        return response;
      }), catchError((err: any) => {
        console.log(err);
        return throwError(err);
      }));
  }

Spring boot

@RequestMapping(value = "/register/mentor", method = RequestMethod.POST,consumes = "application/json")
    @ResponseBody
    public ResponseEntity<?> registerMentor(HttpServletRequest request) throws Exception {
//        connectionValidation.isAdmin();
        StringBuilder builder = new StringBuilder();
        try (BufferedReader in = request.getReader()) {
            char[] buf = new char[4096];
            for (int len; (len = in.read(buf)) > 0; )
                builder.append(buf, 0, len);
        }
        String requestBody = builder.toString();
        return saveMentorUser(new Mentor());
//        return saveMentorUser(mentor);
    }

and I tried this

https://medium.com/@udith.indrakantha/upload-images-and-save-them-in-a-database-angular-8-spring-boot-mysql-b5144768202b

Upvotes: 0

Views: 292

Answers (2)

idan ovadia
idan ovadia

Reputation: 239

I looked in Heroku CLI and I relized that is not a cors problem ,but, one of my function in spring throw an error that connect to Mongo but I guess heroku didnt understand it and respone with cors problem.

Upvotes: 1

vishnu sandhireddy
vishnu sandhireddy

Reputation: 1176

The headers content is being set as JSON, this might have to be set to form-data as your passing form data

    headers = headers.append('Content-type', 'multipart/form-data');

Upvotes: 0

Related Questions