首页 > 解决方案 > 在 web 应用程序中保存图像文件,java

问题描述

在我的网络应用程序中,我希望允许“客户端用户”上传大量图像文件,并且“客户端用户”必须能够看到上传的图像文件网格。

在这种情况下,所有图像文件都有权进行上传、读取、删除和编辑操作。

基本上我正在使用java技术,但我有疑问,

标签: sqlangularjsspringhibernatejakarta-ee

解决方案


转到此存储库并转到display-image-from-db分支。基本方法如下:

  • 在您拥有的实体中:

    @Lob
    private Byte[] image;
    
  • ImageController.java- 你通过一个MultipartFile

    @PostMapping("recipe/{id}/image")
    public String handleImagePost(@PathVariable String id, @RequestParam("imagefile") MultipartFile file){
    
        imageService.saveImageFile(Long.valueOf(id), file);
    
        return "redirect:/recipe/" + id + "/show";
    }
    
  • 调用imageService以保存file作为参数传递的图像。

  • 该服务基本上将图像内容复制到一个字节数组,最后您将该字节数组分配给您的实体。

    @Override
    @Transactional
    public void saveImageFile(Long recipeId, MultipartFile file) {
    
    try {
        Recipe recipe = recipeRepository.findById(recipeId).get();
    
        Byte[] byteObjects = new Byte[file.getBytes().length];
    
        int i = 0;
    
        for (byte b : file.getBytes()){
            byteObjects[i++] = b;
        }
    
        recipe.setImage(byteObjects);
    
        recipeRepository.save(recipe);
    } catch (IOException e) {
        //todo handle better
        log.error("Error occurred", e);
    
        e.printStackTrace();
    }
    }
    

对于完整的源代码,请转到 repo,这肯定会有所帮助。但是我强烈建议将文件存储在磁盘上而不是数据库中。数据库应该只存储文件的路径。对于这样的解决方案,这里有一个例子:link

TL;博士

  • 我强烈建议不要将数据存储在数据库本身中,而是存储在文件系统中。(例如:在文件夹中。)
  • 指南可能也有帮助。
  • 在这里,您可以找到完整的 RESTful 实现。

干杯!


推荐阅读