0

I am trying to convert the uploaded file path in angular to a byte[] array after receiving it as a string in spring boot controller using @RequestParam. I am adding the byte array to object using simple setter in model class. while registering I am getting 400 HttpError Response

Model Class


@Entity
@Table(name="registration")
public class Registration {

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private int id;
    private String name;
    private String username;
    private String password;

    @Lob
    private byte[] image;

 // respective getters,setters and constructor


My Registration Repository


@Repository
public interface RegistrationRepository extends JpaRepository<Registration, Integer> {

    public List<Registration> findByUsernameAndPassword(String username,String password);

}

Registration Service is present

Registration Controller:-


@RestController
@RequestMapping("/register")
@ComponentScan
public class RegistrationController {

    @Autowired
    private RegistrationService res;


    @PostMapping("/registeruser")
    public ResponseEntity<Registration> registeruser(@RequestBody  Registration reg, @RequestParam String filename) throws IOException
    {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

        String userHashedPassword = bCryptPasswordEncoder.encode(reg.getPassword());

        File file = new File(filename);
        byte[] picInBytes = new byte[(int) file.length()];
        FileInputStream fileInputStream = new FileInputStream(file);
        fileInputStream.read(picInBytes);
        fileInputStream.close();

        reg.setImage(picInBytes);


        Registration resm= new Registration(reg.getName(),reg.getUsername(),userHashedPassword, reg.getImage());

        Registration userResp = res.registeruser(resm);
        return new ResponseEntity<Registration>(userResp,HttpStatus.OK);
}
Amax1
  • 17
  • 1
  • 6
  • 1
    [is it required that you store the image in the database](https://stackoverflow.com/questions/3748/storing-images-in-db-yea-or-nay)? you can store an image ID, then shard images to a directory structure optimized for the number of images you plan to store. – mavriksc Jan 06 '20 at 19:34

1 Answers1

0

You are accepting a file name, intstead of actual file. Remove the "filename" from your controller's method and add a parameter Multipart file. Your controller method does this: create a file with name given by the filename argument, which is empty, then gets its size, which is empty again and then reads 0 bytes via the stream.

gygabyte
  • 176
  • 2
  • 12
  • Can you please give a full answer? I am struggling with the code. Also if you could tell me if I need to create a service separately – Amax1 Jan 07 '20 at 04:17