Home > Software engineering >  Updating a table to contain an image
Updating a table to contain an image

Time:10-12

I have successfully created an entity and can post to it. I wish to be able to update a column of the table with a blob file. When I do the post request I get a success response however the row is not updated

This is the entity

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Entity
    @Service
    public class Category {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private long categoryId;
    
        @NotNull
        @Column(unique=true)
        @Size(min = 5, max = 20)
        private String categoryName;
    
        @Column(columnDefinition = "MEDIUMBLOB")
        private byte[] categoryImage;
    
        @NotNull
        @Size(min = 10, max = 50)
        private String categoryDescription;
    }

The PUT request for the image upload

    @PutMapping("/categories/{categoryId}/upload")
    public ResponseEntity<ResponseMessage> uploadImage(@PathVariable("categoryId") long catID,
            @RequestParam() MultipartFile file) {
        Optional<Category> category = catService.listCategoryById(catID);
        if (category.isPresent()) {
            try {
                Category _category = category.get();
                _category.setCategoryImage(imgService.storeImage(file));
                return new ResponseEntity<>(
                        new ResponseMessage("Uploaded "   file.getOriginalFilename()   " successfully!"),
                        HttpStatus.CREATED);

            } catch (Exception e) {

                return new ResponseEntity<>(new ResponseMessage("Failed to upload "   file.getOriginalFilename()   "!"),
                        HttpStatus.EXPECTATION_FAILED);

            }
        } else {
            return new ResponseEntity<>(new ResponseMessage("Category Does not exist"), HttpStatus.NOT_FOUND);
        }
    }

The image service

    @Service
    public class ImageService {
    
        public byte[] storeImage(MultipartFile file) throws IOException {
            return file.getBytes();
        }
    }

When I do the PUT request I get this PUT request pic

However the database is not updated. The image column remains null database row pic

Do you have an idea why?

CodePudding user response:

I don't see service.save() call in your controller code. Are you persisting that _category entity?

try {
      Category _category = category.get();                
      _category.setCategoryImage(imgService.storeImage(file));

      categoryService.save(_category);

      return new ResponseEntity<>(
                        new ResponseMessage("Uploaded "   file.getOriginalFilename()   " successfully!"),
                        HttpStatus.CREATED);

  } catch (Exception e) {

       return new ResponseEntity<>(new ResponseMessage("Failed to upload "   file.getOriginalFilename()   "!"),
                        HttpStatus.EXPECTATION_FAILED);

  }
  • Related