Vishal Torne
Vishal Torne

Reputation: 366

Image uploading and displaying from database H2 error spring boot thymleaf

I am trying to build a Book shop website using Springboot,thymleaf,H2 embedded. When I try to upload the picture of new book category it gives me a null pointer error

this is my Category.class

@Entity
@Table(name="category")
public class Category implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy= GenerationType.AUTO)
@Column(name="ID")
private Long id;

@Size(min=1, max=90)
@Column(name="CATEGORY_NAME")
private String CategoryName;


@Lob
@Column(name="CATEGORY_PHOTO")
private byte[] CategoryPhoto;


public Category(Long id, @Size(min = 1, max = 90) String categoryName, byte[] categoryPhoto) {
    super();
    this.id = id;
    CategoryName = categoryName;
    CategoryPhoto = categoryPhoto;
}

public byte[] getCategoryPhoto() {
    return CategoryPhoto;
}

public void setCategoryPhoto(byte[] categoryPhoto) {
    CategoryPhoto = categoryPhoto;
}

public Category() {}

@OneToMany(mappedBy = "category", cascade=CascadeType.ALL, orphanRemoval=true)
private Set<Book> Books = new HashSet<>();

public Set<Book> getBooks() {
    return Books;
}

CategoryController:

@Controller
@RequestMapping(value="/categories")
public class CategoryController {

private final Logger logger = LoggerFactory.getLogger(BookController.class);

private MessageSource  messageSource;

@Autowired 
private CategoryService categoryService;

@GetMapping
public String list(Model uiModel) {
    logger.info("Listing categories:");
    List<Category> categories = categoryService.findALL();
    uiModel.addAttribute("categories", categories);
    logger.info("No. of categories: " + categories.size());
    return "categories";
}

@GetMapping(value = "/{id}")
public String show(@PathVariable Long id, Model model) {
    Category category = categoryService.findbyID(id);
    
    if(category.getCategoryPhoto() == null) {
        logger.debug("Downloading photo for id: {} with size{}",
          category.getId(), category.getCategoryPhoto().length);
    }
    model.addAttribute("category", category);
    return "showCategory";
}

@GetMapping(value = "/new")
public String create(Model uiModel) {
    logger.info("creating Category ...");
    Category category = new Category();
    uiModel.addAttribute("category", category);
    return "updateCategory";
}

@PostMapping
public String saveCategory(@Valid Category category, BindingResult bindingResult,
        Model uiModel, HttpServletRequest httpServletRequest, RedirectAttributes redirectAttributes,
        Locale locale, @RequestParam(value="file", required=false) Part file) {
    logger.info("Creating Category....");
    if(bindingResult.hasErrors())
    {
        uiModel.addAttribute("message", new Message("error", messageSource.getMessage("category_save_fail", new Object[] {}, locale)));
        uiModel.addAttribute("Category", category);
        return "categories/new";
    }
    uiModel.asMap().clear();
    redirectAttributes.addFlashAttribute("message", new Message("success", messageSource.getMessage("Category_save_success", new Object[] {}, locale)));
    logger.info("Category ID" + category.getId());
    //process upload file 
    if(file != null) {
    logger.info("File name:" + file.getName());
    logger.info("File size:" + file.getSize());
    logger.info("File content type:" + file.getContentType());
    byte[] filecontent = null;
    try
    {
        InputStream inputStream = file.getInputStream();
        if(inputStream == null)
            logger.info("File InputStream is null");
        filecontent = IOUtils.toByteArray(inputStream);
        category.setCategoryPhoto(filecontent);
    }catch(IOException ex) {
        logger.error("Error Saving uploaded file");
    }
    category.setCategoryPhoto(filecontent);
    }
    categoryService.save(category);
    return "redirect:/categories/" + category.getId();
}

}

updatecategories.html page :: used for creating a new category and updating category with Name and Categoryphoto

<form class="form-horizontal" th:object="${category}" th:action="@{/categories}" method="post" enctype="multipart/form-data">
        <input type="hidden" th:field="*{id}"/>
        <div class="form-group">
            <label class="col-sm-2 control-label">Category Name</label>
            <div class="col-sm-10">
                <input class="form-control" th:field="*{CategoryName}"/>
            </div>
        </div>
          <div class="form-group">
            <label class="col-sm-2 control-label">Category Photo</label>
            <div class="col-sm-10">
                <input name="file" type="file" value="upload" class="form-control" th:field="*{CategoryPhoto}"/>
            </div>
        </div>
        <div class="row">
            <button class="btn btn-default">Save</button>
        </div>
    </form>

show Categories.html page for showing the category name and photo after creating or updating

<form class="form-horizontal" th:object="${category}" th:action="@{/categories}" method="post" enctype="multipart/form-data">
        <input type="hidden" th:field="*{id}"/>
        <div class="form-group">
            <label class="col-sm-2 control-label">Category Name</label>
            <div class="col-sm-10">
                <input class="form-control" th:field="*{CategoryName}"/>
            </div>
        </div>
          <div class="form-group">
            <label class="col-sm-2 control-label">Category Photo</label>
            <div class="col-sm-10">
                <input name="file" type="file" value="upload" class="form-control" th:field="*{CategoryPhoto}"/>
            </div>
        </div>
        <div class="row">
            <button class="btn btn-default">Save</button>
        </div>
    </form>

here is a image when I create a new category enter image description here

error Image: enter image description here

sorry for Long Question description but I want to clarify the details. Help would be appreciated.

Upvotes: 0

Views: 326

Answers (1)

Vishal Torne
Vishal Torne

Reputation: 366

I got the mistake I am using MessageSource without autowiring it Done that. And Adding Messages to my properties file.

Upvotes: 1

Related Questions