Spring Boot + Java + PostgreSQL로 DB에 이미지 파일 업로드 및 화면 표시

소개



유저나 상품등의 테이블에 화상의 함께 보존하고 싶어졌으므로, 데이타베이스상에 보존할 수 없는지 여러가지 조사한 결과 어떻게든 그 방법을 알았으므로 비망록으로서의 남겨 둡니다. 누군가의 참고가 되면 생각합니다.

완성 이미지


  • 다음과 같은 화면 파일 업로드 버튼이 있으며 이미지 선택
  • 업로드 버튼을 클릭하면 업로드한 파일이 화면에 표시됩니다.

  • 다음이 필요한 소스 코드입니다.



    이 응용 프로그램에서 웹 응용 프로그램에 이미지를 구현할 수있었습니다 :)
    CREATE TABLE files (
      id SERIAL PRIMARY KEY,
      name VARCHAR,
      type VARCHAR,
      data BYTEA -- ポイント1: 保存したい写真のデータ型をBYTEA(byte array)にする
    );
    
    @Entity
    @Table(name = "files")
    @Getter @Setter @NoArgsConstructor
    public class FileDB {
    
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      private String id;
      private String name;
      private String type;
       
      @Lob // ポイント2: @Lobと@Typeを以下のようにつける(@Lobはサイズが大きいデータのカラムにつけるみたい。@Typeがないと「bigintのデータが出力されてますよ」的なエラーが出る
      @Type(type = "org.hibernate.type.BinaryType")
      @Column(name = "data")
      private byte[] data;
    
      public FileDB(String name, String type, byte[] data) {
        this.name = name;
        this.type = type;
        this.data = data;
      }
    
    }
    
    
    <body><!-- ポイント3: formタグに「enctype="multipart/form-data"」追記 -->
      <form th:action="@{/portfolio/file/upload}" method="POST" enctype="multipart/form-data">
        <input type="file" name="file" id="file">
        <button type="submit">UPLOAD</button>
      </form>
      <div>
        <p th:text="${message}"></p>
        <img th:src="${'data:image/png;base64,'+image}" alt="">
      </div>
    </body>
    
    @Controller
    @RequestMapping("/portfolio/file")
    public class FileController {
      @Autowired  private FileStorageService storageService;
    
      @GetMapping(value="/index")
      public String index(Model m) {
        String path = "";
        m.addAttribute("path", path);
        return "file_upload";
      }
    
      @PostMapping("/upload")
      public String uploadFile(@RequestParam("file") MultipartFile file, Model m) {
        String message = "";
        try {
          FileDB savedFile = storageService.store(file);
          byte[] bytes = savedFile.getData();
          // ポイント4: Base64.getEncoder().encodeToString(bytes)でbyteをStringにして、Viewに渡す
          String image =  Base64.getEncoder().encodeToString(bytes);
          message = "Uploaded the file successfully: " + file.getOriginalFilename();
          m.addAttribute("message", message);
          m.addAttribute("image", image);
          return "file_upload";
        } catch (Exception e) {
          message = "Could not upload the file: " + file.getOriginalFilename() + "!";
          m.addAttribute("message", message);
          return "file_upload";
        }
      }
    }
    
    @Service
    public class FileStorageService {
    
      @Autowired
      private FileDBRepository fileDBRepository;
    
      public FileDB store(MultipartFile file) throws IOException {
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());
        FileDB FileDB = new FileDB(fileName, file.getContentType(), file.getBytes());
    
        return fileDBRepository.save(FileDB);
      }
    
    }
    

    좋은 웹페이지 즐겨찾기