[λ©λͺ¨] π νμΌ μ λ‘λ μ°Έκ³
μμ±μμ΄λμ€μμ±μκ°25.09.29μ‘°νμ20 λͺ©λ‘ λκΈ 01 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | /* μνλ±λ‘ */ // 1. μ
λ‘λ κ²½λ‘ ν보, 2. MultipartFile μ μ₯(UUID + νμ₯μ), 3. voμ μ΄λ―Έμ§ κ²½λ‘ μΈν
, 4. DAO νΈμΆ(DB insert) @Override public int createProduct(ProductVO vo, List<MultipartFile> files, HttpSession session) { // μν κΈ°λ³Έ μ 보 Insert int res = productDAO.insertProduct(vo); if(res == 0) return 0; UserVO loginUser = (UserVO) session.getAttribute("sLoginUser"); // μ
λ‘λ κ²½λ‘ String realPath = session.getServletContext().getRealPath("/resources/data/product"); // λ§μ½ ν΄λΉ κ²½λ‘κ° μ‘΄μ¬νμ§ μμΌλ©΄ μλ‘ μμ±νλ€. // - dir.exists() : ν΄λΉ κ²½λ‘(ν΄λ/νμΌ)κ° μ‘΄μ¬νλμ§ νμΈ // - mkdirs() : ν΄λκ° μμ κ²½μ°, μ€κ° κ²½λ‘κΉμ§ μ λΆ μμ± File dir = new File(realPath); // dir κ²½λ‘λ₯Ό νμΈνκ³ μμΌλ©΄ μ€κ°κ²½λ‘κΉμ§ μμ± if(!dir.exists()) dir.mkdirs(); for(MultipartFile file : files) { if(file == null || file.isEmpty()) continue; // MultipartFile file : ν΄λΌμ΄μΈνΈμμ μ
λ‘λ λ νμΌμ λ΄κ³ μλ κ°μ²΄ // getOriginalFilename: ν΄λΌμ΄μΈνΈμμ μ
λ‘λν μλ³Έ νμΌλͺ
μ κ°μ§κ³ μ΄ String oFileName = file.getOriginalFilename(); // νμΌμ΄ nullμ΄ μλκ³ λΉμ΄μμ§ μμ λλ§ μ²λ¦¬ if(oFileName != null && !oFileName.isEmpty()) { // νμ₯μ μΆμΆ : .jsp, .png λ± νμΌλͺ
μ λ°λμ΄λ νμ₯μλ λμΌνκ² μ¬μ©ν΄μΌ νκΈ° λλ¬Έ String sFileName = oFileName.substring(oFileName.lastIndexOf(".")); // UUID + νμ₯μ μ‘°ν©μΌλ‘ μ νμΌλͺ
μμ± β μ€λ³΅ λ°©μ§ // λ‘κ·ΈμΈλ μ¬μ©μμ idxλ₯Ό μ‘°ν©νμ¬ λκ° μ¬λ Έλμ§ μΆμ / μΈλΆ λ
ΈμΆ μ μ 3μλ idxμ μλ―Έ λͺ¨λ¦. String nFileName = UUID.randomUUID().toString() + "_" + loginUser.getIdx() + sFileName; // μ
λ‘λλ νμΌμ μλ²μ μ μ₯νλ λ¨κ³ // 1. νμΌ κ°μ²΄ μμ± // - File ν΄λμ€λ μ€μ λμ€ν¬(μλ²)μ μ‘΄μ¬ν 'νμΌ'μ κ°λ₯΄ν€λ κ°μ²΄ // - μ¬κΈ°μλ realPath(ν΄λ κ²½λ‘) + nFileName(νμΌ μ΄λ¦) ν©μ³μ κ²½λ‘λ₯Ό μ§μ // - μ΄ μμ μλ νμΌμ΄ "μμ±λ κ²μ²λΌ 보μ΄λ κ°μ²΄"μΌ λΏ, μ€μ λ‘ λμ€ν¬μ μ°μ΄μ§λ μμ File dest = new File(realPath, nFileName); // 2. μ
λ‘λλ νμΌ λ°μ΄ν°λ₯Ό μ€μ μλ²μ μ μ₯ // - transferTo() : MultipartFile μΈν°νμ΄μ€μ μ μλ λ©μλ // - μ
λ‘λλ νμΌμ λ΄μ©μ μμ μ§μ ν file κ°μ²΄(dest) μμΉμ μ μ₯νλ€. // λμλ°©μ : // (1) μ¬μ©μκ° μ
λ‘λν νμΌμ μλ²μ μμ μ μ₯μ(temp)μ 보κ΄λ¨ // (2) transferTo()λ₯Ό νΈμΆνλ©΄ tempμ μλ νμΌ λ°μ΄ν°λ₯Ό dest κ²½λ‘λ‘ λ³΅μ¬/μ΄λ // (3) λ³΅μ¬ ν dest κ²½λ‘μ μ€μ νμΌμ΄ μμ±λ¨ try { file.transferTo(dest); } catch (IOException | IllegalStateException e) { e.printStackTrace(); return 0; } // MultipartFile μ 곡ν΄μ£Όλ transferTo()λ©μλλ‘ In/OutputStreamμ μ¬μ©νμ§ μκ³ μ§μ ν κ²½λ‘μ νμΌμ μ μ₯ ProductImageVO imageVO = new ProductImageVO(); imageVO.setProductId(vo.getProductId()); imageVO.setOriginalName(oFileName); imageVO.setStoredName(nFileName); imageVO.setSize(file.getSize()); productDAO.insertProductImages(imageVO); } } return res; } | cs |
Β
λ€μκ²μ