图像从数据库H2上传和显示错误spring boot thymleaf

时间:2018-08-25 20:31:54

标签: spring-boot model-view-controller thymeleaf h2

我正在尝试使用嵌入式的Springboot,thymleaf,H2建立一个书店网站。当我尝试上传新书类别的图片时,出现空指针错误

这是我的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 页::用于创建新类别并使用名称和类别照片更新类别

<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>

显示Categories.html 页面,用于显示创建或更新后的类别名称和照片

<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>

这是我创建新类别时的图片 enter image description here

错误图片: enter image description here

很抱歉,长问题描述,但我想澄清细节。帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

我在使用MessageSource时没有自动装配它就犯了一个错误。并将消息添加到我的属性文件。