파일 DB 저장
UserUploadController.java
@Autowired
private UserUploadService userUploadService;
@Controller
@RequestMapping(value="user")
public class UserUploadController {
@Autowired
private UserUploadService userUploadService;
UserUploadService.java -- 인터페이스
package user.service;
public interface UserUploadService {
}
UserUploadServiceImpl.java
@Service
package user.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import user.service.UserUploadService;
@Service
public class UserUploadServiceImpl implements UserUploadService {
}
root-context.xml -- 이미 빈 설정 되어있다 !!
<context:component-scan base-package="user.service.impl" />
UserUploadController.java
//DB
userUploadService.upload(imageUploadList);
UserUploadService.java
public void upload(List<UserUploadDTO> imageUploadList);
package user.service;
import java.util.List;
import user.bean.UserUploadDTO;
public interface UserUploadService {
public void upload(List<UserUploadDTO> imageUploadList);
}
UserUploadServiceImpl.java
@Autowired
private UserUploadDAO userUploadDAO;
@Override
public void upload(List<UserUploadDTO> imageUploadList) {
userUploadDAO.write(imageUploadList);
}
package user.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import user.bean.UserUploadDTO;
import user.dao.UserUploadDAO;
import user.service.UserUploadService;
@Service
public class UserUploadServiceImpl implements UserUploadService {
@Autowired
private UserUploadDAO userUploadDAO;
@Override
public void upload(List<UserUploadDTO> imageUploadList) {
userUploadDAO.upload(imageUploadList);
}
}
UserUploadDAO.java -- 인터페이스 DAO의 구현객체를 생성하지 않는다.
@Mapper
package user.dao;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import user.bean.UserUploadDTO;
@Mapper
public interface UserUploadDAO {
void upload(List<UserUploadDTO> imageUploadList);
}
SpringConfiguration.java
@MapperScan("user.dao")
@MapperScan("user.dao")
public class SpringConfiguration {
위 아래 둘 중 하나만 설정하면 된다 !!
root-context.xml
<context:component-scan base-package="user.dao.impl" />
userUploadMapper.xml
<mapper namespace="user.dao.UserUploadDAO">
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="user.dao.UserUploadDAO">
</mapper>
mybatis-config.xml
<typeAlias type="user.bean.UserUploadDTO" alias="upload"/>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias type="user.bean.UserDTO" alias="user"/>
<typeAlias type="user.bean.UserUploadDTO" alias="upload"/>
</typeAliases>
</configuration>
applicationContext.xml 필요없음 지워버리기
mybatis-config.xml ====> 제거
<!-- <typeAliases>
<typeAlias type="user.bean.UserDTO" alias="user"/>
<typeAlias type="user.bean.UserUploadDTO" alias="upload"/>
</typeAliases> --> 주석걸기
SpringConfiguration.java
sqlSessionFactoryBean.setTypeAliasesPackage("user.bean");
user.bean.UserDTO => userDTO 이런식으로 된다 !!
sqlSessionFactoryBean.setTypeAliasesPackage("*.bean"); 이렇게 잡아도된다 !!
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());
sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("spring/mybatis-config.xml"));
sqlSessionFactoryBean.setMapperLocations(new ClassPathResource("mapper/userMapper.xml"));
//sqlSessionFactoryBean.setTypeAliasesPackage("user.bean");
sqlSessionFactoryBean.setTypeAliasesPackage("*.bean");
return sqlSessionFactoryBean.getObject(); // SqlSessionFactory 변환 역할
}
userUploadMapper.xml이 있는지를 알려줘야 한다 !!!
1개면 밑에처럼 적으면 되지만
sqlSessionFactoryBean.setMapperLocations(new ClassPathResource("mapper/userMapper.xml"));
Mapper.xml이 2개 이상일 때는 배열로 잡아줘야 한다.
sqlSessionFactoryBean.setMapperLocations(
new ClassPathResource("mapper/userMapper.xml"),
new ClassPathResource("mapper/userUploadMapper.xml"));
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());
sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("spring/mybatis-config.xml"));
//1개
//sqlSessionFactoryBean.setMapperLocations(new ClassPathResource("mapper/userMapper.xml"));
//Mapper.xml이 2개 이상일 때
sqlSessionFactoryBean.setMapperLocations(
new ClassPathResource("mapper/userMapper.xml"),
new ClassPathResource("mapper/userUploadMapper.xml"));
//sqlSessionFactoryBean.setTypeAliasesPackage("user.bean");
sqlSessionFactoryBean.setTypeAliasesPackage("*.bean");
return sqlSessionFactoryBean.getObject(); // SqlSessionFactory 변환 역할
}
저렇게 여러번 쓰는 것보다 와일드 카드 쓰는게 더 좋다 !!
import org.springframework.context.ApplicationContext; -- 이거 조심 !
@Autowired
private ApplicationContext context; -- 이렇게 하면 스프링이 준다 !!!
sqlSessionFactoryBean.setMapperLocations(
context.getResources("classpath:mapper/*Mapper.xml"));
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());
sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("spring/mybatis-config.xml"));
//1개
//sqlSessionFactoryBean.setMapperLocations(new ClassPathResource("mapper/userMapper.xml"));
//Mapper.xml이 2개 이상일 때
/*
sqlSessionFactoryBean.setMapperLocations(
new ClassPathResource("mapper/userMapper.xml"),
new ClassPathResource("mapper/userUploadMapper.xml"));
*/
sqlSessionFactoryBean.setMapperLocations(context.getResources("classpath:mapper/*Mapper.xml"));
//sqlSessionFactoryBean.setTypeAliasesPackage("user.bean");
sqlSessionFactoryBean.setTypeAliasesPackage("*.bean");
return sqlSessionFactoryBean.getObject(); // SqlSessionFactory 변환 역할
}
userMapper.xml
resultType="userDTO" 위에서 TypeAliase 설정으로 인해 UserDTO가 userDTO로 설정되기 때문에 다 다시 바꿔줘야한다 !!!
<mapper namespace="user.dao.UserDAO">
<!-- 중복 아이디 체크 -->
<select id="getExistId" parameterType="String" resultType="userDTO">
SELECT * FROM usertable WHERE id = #{id};
</select>
UserUploadServiceImpl.java
@Override
public void upload(List<UserUploadDTO> imageUploadList) {
userUploadDAO.upload(imageUploadList);
}
package user.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import user.bean.UserUploadDTO;
import user.dao.UserUploadDAO;
import user.service.UserUploadService;
@Service
public class UserUploadServiceImpl implements UserUploadService {
@Autowired
private UserUploadDAO userUploadDAO;
@Override
public void upload(List<UserUploadDTO> imageUploadList) {
userUploadDAO.upload(imageUploadList);
}
}
UserUploadDAO.java
public void upload(List<UserUploadDTO> imageUploadList);
package user.dao;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import user.bean.UserUploadDTO;
@Mapper
public interface UserUploadDAO {
public void upload(List<UserUploadDTO> imageUploadList);
}
userUploadMapper.xml
SQL문을 실행할 때, 넘어오는 파라메터 타입이 List일 경우
foreach 태그의 collection 속성에 사용할 수 있는 이름은 list 또는 collection이 가능하다.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="user.dao.UserUploadDAO">
<insert id="upload" parameterType="list">
INSERT INTO userUpload (imageName, imageContent, imageFileName, imageOriginalFileName)
VALUES
<foreach collection="list" item="dto" separator=",">
(#{dto.imageName}, #{dto.imageContent}, #{dto.imageFileName}, #{dto.imageOriginalFileName})
</foreach>
</insert>
</mapper>
uploadAJax.js
location.href = "/spring2/user/uploadList";
$(function(){
$('#uploadAJaxBtn').click(function(){
let formData = new FormData($('#uploadAJaxForm')[0]);
$.ajax({
type: 'post',
enctype: 'multipart/form-data',
processData: false,
contentType: false,
url: '/spring2/user/upload',
data: formData,
success: function(data){
//alert(data);
location.href = "/spring2/user/uploadList";
},
error: function(e){
console.log(e);
}
});//$.ajax
});
});
UUID
UserUploadController.java
String imageFileName;
for(MultipartFile img: list) {
imageFileName = UUID.randomUUID().toString();
dto.setImageFileName(imageFileName);
//1개 또는 여러개(드래그해서 넘어오는 경우)
//파일명에 한글 또는 공백이 있어도 업로드가 된다.
@ResponseBody
@RequestMapping(value = "upload", method = RequestMethod.POST, produces = "text/html; charset=UTF-8")
public String upload(@ModelAttribute UserUploadDTO userUploadDTO,
@RequestParam("img[]") List<MultipartFile> list,
HttpSession session) {
//실제폴더
String filePath = session.getServletContext().getRealPath("WEB-INF/storage");
System.out.println("실제 폴더 = " + filePath);
String imageFileName;
String imageOriginalFileName;
File file;
String result = "";
//파일들을 모아서 DB로 보내기
List<UserUploadDTO> imageUploadList = new ArrayList<>();
for(MultipartFile img: list) {
imageFileName = UUID.randomUUID().toString();
imageOriginalFileName = img.getOriginalFilename();
file = new File(filePath, imageOriginalFileName);
try {
img.transferTo(file);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//try {
result += "<span>"
+ "<img src='/spring2/storage/"
+ imageOriginalFileName
//+ URLEncoder.encode(imageOriginalFileName, "UTF-8") => 이 방법은 파일명에 공백이 있으면 안된다.
+ "' width='300' height='300'"
+ "</span>";
//} catch (UnsupportedEncodingException e) {
// e.printStackTrace();
//}
//
UserUploadDTO dto = new UserUploadDTO();
dto.setImageName(userUploadDTO.getImageName());
dto.setImageContent(userUploadDTO.getImageContent());
dto.setImageFileName(imageFileName);
dto.setImageOriginalFileName(imageOriginalFileName);
imageUploadList.add(dto);
}//for
//DB
userUploadService.upload(imageUploadList);
return result;
}
이미지 출력
UserUploadController.java
@RequestMapping(value = "uploadList", method = RequestMethod.GET)
public List<UserUploadDTO> uploadList() {
return userUploadService.uploadList();
}
UserUploadService.java
public List<UserUploadDTO> uploadList();
package user.service;
import java.util.List;
import user.bean.UserUploadDTO;
public interface UserUploadService {
public void upload(List<UserUploadDTO> imageUploadList);
public List<UserUploadDTO> uploadList();
}
UserUploadServiceImpl.java
@Override
public List<UserUploadDTO> uploadList() {
return userUploadDAO.uploadList();
}
package user.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import user.bean.UserUploadDTO;
import user.dao.UserUploadDAO;
import user.service.UserUploadService;
@Service
public class UserUploadServiceImpl implements UserUploadService {
@Autowired
private UserUploadDAO userUploadDAO;
@Override
public void upload(List<UserUploadDTO> imageUploadList) {
userUploadDAO.upload(imageUploadList);
}
@Override
public List<UserUploadDTO> uploadList() {
return userUploadDAO.uploadList();
}
}
UserUploadDAO.java
List<UserUploadDTO> uploadList();
package user.dao;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import user.bean.UserUploadDTO;
@Mapper
public interface UserUploadDAO {
public void upload(List<UserUploadDTO> imageUploadList);
List<UserUploadDTO> uploadList();
}
userUploadMapper.xml
<select id="uploadList" resultType="userUploadDTO">
SELECT * FROM userUpload order by seq desc
</select>
UserUploadController.java
@RequestMapping(value = "uploadList", method = RequestMethod.GET)
public ModelAndView uploadList() {
List<UserUploadDTO> list = userUploadService.uploadList();
ModelAndView mav = new ModelAndView();
mav.addObject("list", list);
mav.setViewName("/upload/uploadList");
return mav;
}
uploadList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>이미지 리스트</title>
<link rel="stylesheet" href="../css/uploadFormList.css">
</head>
<body>
<div class="container">
<table>
<thead>
<tr>
<th>번호</th>
<th>이미지</th>
<th>상품명</th>
</tr>
</thead>
<tbody>
<c:forEach var="userUploadDTO" items="${list}">
<tr>
<td>${userUploadDTO.seq}</td>
<td>
<a href="/spring2/storage/${userUploadDTO.imageOriginalFileName}" target="_blank">
<img src="/spring2/storage/${userUploadDTO.imageOriginalFileName}" width="100" height="100" alt="${userUploadDTO.imageName}">
</a>
</td>
<td>${userUploadDTO.imageName}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</body>
</html>
uploadFormList.css
@charset "UTF-8";
body {
background-color: #FFE2FA;
font-family: 'Arial', sans-serif;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
flex-direction: column;
}
table {
border-collapse: collapse;
width: 600px;
background-color: white;
padding: 20px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
border-radius: 10px;
margin-bottom: 20px;
margin-top: 800px;
}
th, td {
padding: 10px;
border: 1px solid #CCC;
text-align: center;
font-size: 14px;
}
th {
background-color: #F2F2F2;
color: #333;
font-size: 16px;
}
img {
border-radius: 8px;
cursor: pointer;
transition: transform 0.3s;
}
img:hover {
transform: scale(1.1);
}
'Spring' 카테고리의 다른 글
DAY 68 - 스프링 프레임워크 HOMEWORK - NCP 파일 삭제 (2024.10.14) (0) | 2024.10.15 |
---|---|
DAY 68 - 스프링 프레임워크 - NCP 파일 업로드 / 수정 (2024.10.14) (4) | 2024.10.15 |
DAY 67 - 스프링 프레임워크 - 파일업로드 (2024.10.11) (0) | 2024.10.11 |
DAY 66 - 스프링 프레임워크 MVC HOMEWORK - 회원탈퇴 (2024.10.10) (1) | 2024.10.11 |
DAY 66 - 스프링 프레임워크 MVC- 회원가입 / 회원목록 / 회원정보수정 (2024.10.10) (1) | 2024.10.10 |