Spring Boot + Java + PostgreSQL로 DB에 이미지 파일 업로드 및 화면 표시
12018 단어 PostgreSQL자바스크립트spring-boot
소개
유저나 상품등의 테이블에 화상의 함께 보존하고 싶어졌으므로, 데이타베이스상에 보존할 수 없는지 여러가지 조사한 결과 어떻게든 그 방법을 알았으므로 비망록으로서의 남겨 둡니다. 누군가의 참고가 되면 생각합니다.
완성 이미지
다음이 필요한 소스 코드입니다.
이 응용 프로그램에서 웹 응용 프로그램에 이미지를 구현할 수있었습니다 :)
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);
}
}
Reference
이 문제에 관하여(Spring Boot + Java + PostgreSQL로 DB에 이미지 파일 업로드 및 화면 표시), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://qiita.com/memorandum0134/items/5c4a741e7e292f6cc9f6
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
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);
}
}
Reference
이 문제에 관하여(Spring Boot + Java + PostgreSQL로 DB에 이미지 파일 업로드 및 화면 표시), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/memorandum0134/items/5c4a741e7e292f6cc9f6텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)