Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting Image to the MySQL database via Spring Boot

I want to store image as a blob in MySQL database using Spring Boot. I have created the following model to perform crud operations on the database.

import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.Lob;
    import javax.persistence.Table;

import org.hibernate.annotations.DynamicUpdate;

import com.fasterxml.jackson.annotation.JsonIgnore;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Entity
@Table(name="user")
@DynamicUpdate(true)
@AllArgsConstructor
@Data
@NoArgsConstructor
@ToString
public class Users {

    @Id
    @GeneratedValue
    @Column(name="u_id")
    private Integer userId;
    @Column(name="f_nme")
    private String fNme;
    @Column(name="l_nme")
    private String lNme;
    @Column(name="email")
    private String email;
    @Column 
    @JsonIgnore
    private String password;
    @Column(name="cntry")
    private String country;
    @Column(name="type")
    private String type;
    @Lob
    @Column(name="prof_pic")
    private byte[] profPic;

    public Users() {}

    public Integer getId() {
        return userId;
    }

    public void setId(Integer id) {
        this.userId = id;
    }

    public String getfNme() {
        return fNme;
    }

    public void setfNme(String fNme) {
        this.fNme = fNme;
    }

    public String getlNme() {
        return lNme;
    }

    public void setlNme(String lNme) {
        this.lNme = lNme;
    }


    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }


    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public byte[] getProfPicPath() {
        return profPic;
    }

    public void setProfPicPath(byte[] profPic) {
        System.out.println(profPic);
        this.profPic = profPic;
        System.out.println(this.profPic);
    }

}

And the following is my UserDTO class.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.springframework.web.multipart.MultipartFile;

public class UserDTO {
    private String userID;
    private String email;
    private String password;
    private String country;
    private String fName;
    private String lName;
    private String type;
    private String profPicPath;

    public String getEmail() {
        return email;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getfName() {
        return fName;
    }

    public void setfName(String fName) {
        this.fName = fName;
    }

    public String getlName() {
        return lName;
    }

    public void setlName(String lName) {
        this.lName = lName;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getProfPicPath() {
        return profPicPath;
    }

    public void setProfPicPath(String profPicPath) {
        this.profPicPath = profPicPath;
    }

    public String getUserID() {
        return userID;
    }

    public void setUserID(String userID) {
        this.userID = userID;
    }
}

My REST API to update the database is listed below.

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.elmbridge.PropertyManagementSystem.model.UserDTO;
import com.elmbridge.PropertyManagementSystem.repository.SearchRepository;
import com.elmbridge.PropertyManagementSystem.service.JwtUserDetailsService;
@CrossOrigin(origins = "http://localhost:4200")
@RestController
public class DashboardController {


    @Autowired
    private JwtUserDetailsService userDetailsService;

    private UserDTO userR;

    @Autowired                                                                                  
    private SearchRepository user;


    @GetMapping("/country/{email}")
    public ResponseEntity<String> getCountry(@PathVariable("email") String email) {
        return ResponseEntity.ok(user.findCountryByEmail(email));
    }

    @PutMapping("/profile-picture/{email}")
    public void uploadImage(@RequestParam("file") MultipartFile imageFile, @PathVariable("email") String email) {
     try {
        byte[] img = imageFile.getBytes();
        System.out.println(img);
        userDetailsService.saveImg(img, email);
          System.out.println("Image saved");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }    

    }

The Image is not inserted to the database. I checked whether the image is received to the user model by using print statements and found that the image is received without a problem. I have set the data type of the field which intended to save the image in my MySQL database as long blob. Can someone point me out whats wrong in here please ?

like image 769
Pegasus008 Avatar asked Nov 07 '22 12:11

Pegasus008


1 Answers

you can use this code .. for solve your problem

@PostMapping("/profile-picture")
    public ResponseEntity uploadImage(@RequestParam("file") MultipartFile imageFile, @ModelAttribute UserDTO requestDto) {
     try {
          UserDTO created  =userDetailsService.saveImg(requestDto, file.getBytes());
          return new ResponseEntity<>(created, HttpStatus.OK);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }    
    return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}

also you must add in your Class UserDTO

private byte[] profPic;

like image 194
devdev Avatar answered Nov 14 '22 22:11

devdev