package com.brogrammers.brogrammers.domain.product;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Entity
@Data
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Imgs { // 이미지 테이블
@Id @GeneratedValue
@Column(name="imgs_id")
private Long id;
@ManyToOne
@JoinColumn(name="products_id")
private Products products; // 상품 외래키
@Column(name="original_name") //원본 이름
private String originName;
@Column(name="save_name") // 저장 이름
private String saveName;
@Column(name="img_size")
private Long size;
@Column(name="img_path")
private String path;
@Builder
public Imgs(String originName, String saveName, String path, Long size,Products products){
this.originName = originName;
this.saveName = saveName;
this.path = path;
this.size = size;
this.products = products;
}
}
1. 이미지 저장 테이블을 작성
originName : 실제 파일 이름 / saveName : 저장 이름
package com.brogrammers.brogrammers.domain.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
private String resourcePath = "/upload/**"; // view에서 접근할 경로
private String savePath = "file:///D:/spring/imgs/"; // 실제 경로
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(resourcePath)
.addResourceLocations(savePath);
}
}
2. config/WebConfig 클래스 작성. (view 페이지에서 사용할 클래스)
package com.brogrammers.brogrammers.web.products;
import com.brogrammers.brogrammers.domain.member.Member;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.multipart.MultipartFile;
import java.util.Optional;
@Data
@NoArgsConstructor
public class ProductForm {
private String productBrand;
private String productName;
private String productColor;
private int size;
private int stockQuantity;
private int price;
private Member member; // 등록 회원이 누구인지 식별하기 위한 회원
@Builder
public ProductForm(String productBrand, String productName, String productColor, int size, int stockQuantity, int price, Optional<MultipartFile[]> imgs) {
this.productBrand = productBrand;
this.productName = productName;
this.productColor = productColor;
this.size = size;
this.stockQuantity = stockQuantity;
this.price = price;
this.imgs = imgs;
}
// 사진 등록
private Optional<MultipartFile[]> imgs; // html -> Controller 파일 담는 용도
}
3. ProductForm 클래스 작성. (DTO)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>상품등록</title>
<th:block th:replace="include/header :: header"></th:block>
</head>
<body>
<th:block th:replace="include/bodyHead :: bodyHeader"></th:block>
<h2>상품등록 페이지</h2>
<form th:action="@{/products/add}" method="post" th:object="${form}" enctype="multipart/form-data">
<div>
<label th:for="productBrand">브랜드:</label> <!-- 텍스트로 입력하지 않고 불러오는 방법 생각하기-->
<input type="text" th:field="*{productBrand}" >
<div class="field-error" th:errors="*{productBrand}" />
</div>
<div>
<label th:for="productName">상품 이름:</label>
<input type="text" th:field="*{productName}" >
<div class="field-error" th:errors="*{productName}" />
</div>
<div>
<label th:for="productColor">색상:</label>
<input type="text" th:field="*{productColor}" >
<div class="field-error" th:errors="*{productColor}" />
</div>
<div>
<label th:for="size">사이즈:</label>
<input type="text" th:field="*{size}">
<div class="field-error" th:errors="*{size}" />
</div>
<div>
<label th:for="stockQuantity">수량:</label>
<input type="text" th:field="*{stockQuantity}">
<div class="field-error" th:errors="*{stockQuantity}" />
</div>
<div>
<label th:for="price">가격:</label>
<input type="text" th:field="*{price}">
<div class="field-error" th:errors="*{price}" />
</div>
<div>
<input type="file" name="imgs" multiple>
</div>
<button type="submit">등록</button>
</form>
<a href="#">링크</a>
</body>
</html>
4. 상품등록 페이지
form에 enctype="multipart/form-data" 추가, input type="file" , name은 Productform 클래스에 있는 items와 같게,
multiple로 사진 여러장 업로드 가능하게 하기.
@PostMapping("/products/add")
public String add(@Valid @ModelAttribute("form") ProductForm form , HttpServletRequest request, Model model) throws Exception{
Member member = getMember(request); // 조회된 회원 아이디
Products products = new Products();
form.setMember(member); // 상품 등록할 때 회원 아이디 입력하기
products.saveProduct(form.getProductName(), form.getProductBrand(),form.getProductColor(),form.getPrice(),form.getSize(), form.getStockQuantity(),form.getMember());
products.saveImgs();
List<Imgs> list = new ArrayList<>();
Imgs imgs = null;
productService.save(products); // 상품의 아이디
if(form.getImgs().isPresent()){ // 사진이 업로드가 됐으면
MultipartFile[] files = form.getImgs().get();
for(MultipartFile file : files){
String saveName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
String path = "D:/spring/imgs/" + saveName;
imgs = Imgs.builder()
.originName(file.getOriginalFilename())
.saveName(saveName)
.products(products)
.path(path)
.size(file.getSize())
.build();
imgService.save(imgs);
file.transferTo(new File(path)); // 파일 저장
list.add(imgs);
}
}
model.addAttribute("imgs",list);
model.addAttribute("mgs","상품 등록이 완료되었습니다.");
model.addAttribute("product",products);
return "products/detail"; // 상품 상세보기 페이지로 넘어갈 예정
}
System.currentTimeMillis() : 현재 시간, file.getOriginalFilename() : 오리지날 파일 네임
path : 실제 저장 경로(현재는 외부 경로), file.transferTo(New File(path)) : 파일 저장
detail 페이지 이동하기 전에 이미지 리스트 model.addAttribute로 담아주기
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>로그인</title>
<th:block th:replace="include/header :: header"></th:block>
</head>
<body>
<th:block th:replace="include/bodyHead :: bodyHeader"></th:block>
<h2 th:text="${msg}">상품등록(디테일) 페이지 </h2>
<div class="form-group">
<div>상품id</div>
<div th:text="${product.id}"></div>
<div>상품이름</div>
<div th:text="${product.name}"></div>
<div>브랜드</div>
<div th:text="${product.brand}"></div>
<div>상품이미지</div>
<img th:src="@{${product.filePath}}"/>
<div th:each="img : ${imgs}">
<img th:src="@{|/upload/${img.saveName}|}"/>
</div>
<a href="#" th:href="@{/products/{id}/edit (id=${product.id})}" class="btn btn-primary" role="button">
수정
</a>
</div>
</body>
</html>
상품 등록 후 상세 보기 페이지로 넘어오기
'프로젝트' 카테고리의 다른 글
[개인 프로젝트] 중고 거래 사이트 만들기. ( ~ 2.5) (0) | 2024.01.15 |
---|---|
Spring Boot 2.7 -> Spring Boot 3.2 마이그레이션 (0) | 2024.01.05 |
Input 컴포넌트 (1) | 2023.12.05 |
컴포넌트 만들기(게시물 목록)-1 (1) | 2023.12.05 |
Spring Security.. (1) | 2023.12.01 |