Here is my Post class Entity.
The aim is to send images to the database through an API endpoint that I will youse in my website.
@Entity(name = "posts")
public class Post {
@Id
@Column(name = "Id", nullable = false)
private String id;
@Column(name = "Post_title", nullable = false)
private String title;
@Column(name = "creator", nullable = false)
private String creator;
@Lob
@Column(name = "post_image", nullable = false)
private Byte[] postImage;
@Column(name = "descriptions", nullable = false)
private String descriptions;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public Byte[] getPostImage() {
return postImage;
}
public void setPostImage(Byte[] postImage) {
this.postImage = postImage;
}
public String getDescriptions() {
return descriptions;
}
public void setDescriptions(String descriptions) {
this.descriptions = descriptions;
}
}
This is the java spring controller for the api
The plan is to convert the image with javaScript, I want to have less java code
@RestController
@RequestMapping("/api/posts")
public class PostController {
@Autowired
private PostRepository postRepository;
@PostMapping
public ResponseEntity<Post> createPost(@RequestBody Post post) {
Post newPost = postRepository.save(post);
return new ResponseEntity<>(newPost, HttpStatus.CREATED);
}
}
here is how I implemented the convention of images into a byte
const inputElement = document.getElementById("image-input");
inputElement.addEventListener("change", function() {
const file = inputElement.files[0];
const reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = function() {
const blob = new Blob([reader.result], { type: file.type });
const byteArray = new Uint8Array(blob);
// Now you can send the byteArray to your API endpoint
};
});