java - 将图片存储在H2数据库spring boot thymeleaf中

标签 java spring-mvc spring-boot thymeleaf h2

美好的一天。我想将图像存储在 h2 数据库中,然后在 html 页面中检索并显示相同的图像。我正在使用 spring boot 和文件上传方法,但在绑定(bind)结果中出现错误

这是页面/类:

分类.java

package com.vishal.project.entities;

@Entity
@Table(name="category")
public class Category implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
@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;
}

public void setBooks(Set<Book> books) {
    Books = books;
}

public Long getId() {
    return id;
}
public void setCategoryID(Long id) {
    this.id = id;
}
public String getCategoryName() {
    return CategoryName;
}
public void setCategoryName(String categoryName) {
    CategoryName = categoryName;
}

@Override
public String toString() {

    return "Category ID:" + id + 
           "Category Name:"+ CategoryName;
}


}

分类 Controller .java

package com.vishal.project.web;


import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.vishal.project.entities.Category;
import com.vishal.project.services.CategoryService;
import com.vishal.project.util.Message;


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


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

@Autowired
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}" , consumes="Multipart/formdata")
public String show(@PathVariable Long id, Model model) {
    Category category = categoryService.findbyID(id);


    model.addAttribute("category", category);
    return "showCategory";
}

@GetMapping(value = "/edit/{id}")
public String updateForm(@PathVariable Long id, Model model) {
    model.addAttribute("category", categoryService.findbyID(id));
    return "updateCategory";
}

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

    uiModel.addAttribute("category", category);
    return "updateCategory";
}


@PostMapping(value = "/upload")
public String saveCategory(@Valid @ModelAttribute("category") Category category, BindingResult bindingResult,
        Model uiModel, HttpServletRequest httpServletRequest, RedirectAttributes redirectAttributes,
        Locale locale, @RequestParam(value="file", required=true) MultipartFile file) {
    logger.info("Creating Category....");
    logger.info("Category ID" + category.getId());
    logger.info("Category ID" + category.getCategoryName());
    logger.info("Category ID" + category.getCategoryPhoto());
    if(bindingResult.hasErrors())
    {
        logger.info("Error:", bindingResult.getAllErrors());
        logger.debug("field Error:", bindingResult.getFieldError());
        uiModel.addAttribute("message", new Message("error", messageSource.getMessage("category_save_fail", new Object[] {}, locale)));
        uiModel.addAttribute("category", category);
        return "updateCategory";
    }
    uiModel.asMap().clear();
    redirectAttributes.addFlashAttribute("message", 
            new Message("success", messageSource.getMessage("Category_save_success", new Object[] {}, locale)));
    //process upload file 
    logger.info("File Name :", file.getName() );
    logger.info("File Size :", file.getSize() );
    logger.info("File content type :", file.getContentType() );
    if(file != null) {
    byte[] filecontent = null;
    try
    {
        InputStream inputStream = file.getInputStream();
        if(inputStream == null) 
            logger.debug("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().toString();
}

category Image

categoryShow.page

<body>
<div th:replace="fragments/header_admin :: header_admin">Header</div>
<div class="container">

<h1>Category Details</h1>

<div>
    <form class="form-horizontal" th:object="${category}" >
    <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">
                <p class="form-control-static" th:text="${CategoryName}"> 
</p></div>
        </div>

        <div class="form-group">
            <label class="col-sm-2 control-label" >Category Photo</label>
            <div class="col-sm-10">
                <p class="form-control-static" ><img alt="CatName" 
  th:src="@{CategoryPhoto}" /> </p></div>
        </div>
    </form>
</div>

categoryUpdate 页面(创建或更新带有详细信息和图像的类别)

<div class="container">

<h1>Category Details</h1>

<div>
    <form  class="form-horizontal" th:object="${category}" th:action="@{/categories/upload}" 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" class="form-control" th:field="*{CategoryPhoto}"/>
            </div>
        </div>
        <div class="row">
            <button class="btn btn-default">Save</button>
        </div>
    </form>
</div>
<div th:insert="~{fragments/footer :: footer}">&copy; 2017 Iuliana Cosmina & Apress</div>

错误:我进入了 CategoryController.saveCategory() 方法的 bindingResult。

当我调试代码时出现错误。这里有一张图片来演示:

enter image description here

我很难使用 thymleaf 在 CategoryShow 页面上显示图像。 任何帮助将不胜感激。

更新:谁能告诉我这个错误是什么意思,请:

Failed to convert property value of    type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'byte[]' for property 'CategoryPhoto'; nested exception is 
java.lang.IllegalArgumentException: Cannot convert value of type 'org.springframework.web.multipart.support.
StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'byte' for property
'CategoryPhoto[0]': PropertyEditor [org.springframework.beans.propertyeditors.CustomNumberEditor] returned 
inappropriate value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' 

**最终更新:我收到此错误:**所需的请求部分"file"不存在

最佳答案

你总是可以做的是比较工作文件上传example和你的。

另一件事有助于将您的输入名称与您的 Controller 方法期望您的文件的名称进行比较。

如果您发布的代码仍然相关,您可以在模板中的文件输入中找到名称“Fileimport”,但在您的 Controller 中您需要文件 (@RequestParam(value="file", required=false) )。

其他有助于调试的东西:

  • 使用浏览器的开发者工具并查看您通过网络发送的内容
  • 日志incoming requests在服务器端(以这种方式,或者对您来说太复杂,您可以简单地遍历参数名称并记录它们(如果可能,也记录它们的值)

如果这对您没有帮助,那么请更新帖子:更新您的代码(模板 + Controller ,如果更改)并使用更好的堆栈跟踪:更好我的意思是您不应该只显示最后 N 行stacktrace,但至少到执行代码的第一行(换句话说,类名以您的包开头),如果第一个 Caused by 或第二个有意义的话就更好了。

关于java - 将图片存储在H2数据库spring boot thymeleaf中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52114455/

相关文章:

Spring RedisTemplate : use same key with multiple RedisTemplate to store different values

java - 在 Spring 中返回一个没有重定向的静态 html

javascript - 尝试将 React/Ajax 调用与 Spring MVC 和 Thymeleaf 结合使用

java - Apache Camel : What is the best way to reuse Camel routes from other routes?

java - SpringBoot 2.15 中 RestTemplateBuilder 中的类转换问题

Java 9 : Generating a runtime image with JLink using 3rd party jars

java - JTable 不会跨越 JFrame 的边界

java - 无法检索 urlencoded 变音符号。 [解决方案: use UTF8]

java - Spring Boot 不在 Tomcat 实例中启动

java - 如何配置 jackson 以将 Enum 转换为 JSON?