0

I am new to Angular/Spring and have to store (H2-Database) an image (jpeg/png) and I am not quite sure how I should manage to do this. I get my file in the template as:

<input #img type = "file"  accept="image/jpeg,image/png"  (change)="onFileSelected($event)">

My component-class looks like this:

private userDto: User = {
    id: 0,
    name: null,
    img: null
  }

  save(name:string){
      this.userDto.name = name;
      this.userService.saveUser(this.userDto).subscribe(
        newUser => this.createdUser = newUser)
  }

  onFileSelected(event){
    this.user.img = event.target.files[0];
  }

And my service(simplified):

saveUser(user: User): Observable<User>{
    return this.http.post<User>(this.userURI, user);
  }

I catch the post in Spring using @PostMapping/@RequestBody. My question now is: Which type do I have to send and use in Angular and Spring [java], that I can store the image in the backend and display the image I just stored when it is returned. (Or what I am doing wrong?) Sorry for the maybe dump question, but I never used neither Angular or Spring before. Thanks in Advance

1
  • In the frontend you usually have a blob, in the backend a byte[] for the image. Commented Mar 13, 2020 at 17:17

1 Answer 1

2
uploadFile( file: File , id : number ) : Observable<any>  
  {  
    let url = this.baseUrl + "uploadImage/" + id ;  

    const formdata: FormData = new FormData();  

    formdata.append('file', file);  

    return this.http.post(url , formdata);  
  }  

the file argument of type File is retrieved in event.target.files.item(0)

check this for more details : https://www.javatpoint.com/angular-spring-file-upload-example

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.