파일컨트롤러 생성
Apache Commons FileUpload & Apache Commons IO
라이브러리 설치
스프링에서는
cos.jar를 쓸수도 있지만
아파치 커먼 파일업로드 라이브러리가 더 권장
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
pom.xml
Apache Commons FileUpload는 커먼스 IO에 의존성을 갖고 있다.
(그냥 실행하면 class not found 나온다!)
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.7</version>
</dependency>
servlet-context.xml
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="maxUploadSize" value="10485760"/>
</beans:bean>
저장 경로 설정
파일이름 중복 줄이기 (밀리세컨드값 붙여서)
String systemFileName = System.currentTimeMillis()+"_"+file.getOriginalFilename();
경로가 존재하지 않는다면 만들어 주기
if(!tempFilePath.exists()) {tempFilePath.mkdir();}
package kh.spring.controller;
import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileController {
@Autowired
private HttpSession session;
@RequestMapping("fileUpload")
public String fileUpload(String writer, String contents, MultipartFile file) throws Exception{
String filePath = session.getServletContext().getRealPath("upload");
File tempFilePath = new File(filePath);
if(!tempFilePath.exists()) {tempFilePath.mkdir();}
String systemFileName = System.currentTimeMillis()+"_"+file.getOriginalFilename();
File targetLoc = new File(filePath+"/"+systemFileName);
file.transferTo(targetLoc);
return "home";
}
}
업로드 경로
Q. 회원별 폴더 만들기
아이디로 폴더를 만들고 경로에 넣기
Q. 특정 파일만 올리려고 하는 경우?
매개변수 3개나 받는 것보다는 DTO로 받는게 좋다
public String fileUpload(String writer, String contents, MultipartFile file)
멀티파트 자체가 클래스 의존적임
파일 여러개를 업로드 하는 경우
@RequestMapping("filesUpload")
public String filesUpload(MultipartFile[] files) throws Exception{
String filePath = session.getServletContext().getRealPath("upload");
for(MultipartFile file : files) {
System.out.println(file.getOriginalFilename());
//file.transferTo(new File());
String systemFileName = System.currentTimeMillis()+"_"+file.getOriginalFilename();
File targetLoc = new File(filePath+"/"+systemFileName);
file.transferTo(targetLoc);
}
return "home";
}
빈 파일 생성 차단
@RequestMapping("filesUpload")
public String filesUpload(MultipartFile[] files) throws Exception{
String filePath = session.getServletContext().getRealPath("upload");
for(MultipartFile file : files) {
if(!file.isEmpty()) {
System.out.println(file.getOriginalFilename());
String systemFileName = System.currentTimeMillis()+"_"+file.getOriginalFilename();
File targetLoc = new File(filePath+"/"+systemFileName);
file.transferTo(targetLoc);
}
}
return "home";
}
※ 폼의 name과 매개변수의 이름 같아야 연결된다 (file / files 확인)
❔ 파일 네임이 같으면 덮어쓰기?
드문 경우지만 그럴때 파일이름 변경해서 중복 피하기
UUID를 어떻게 믿지?
UUID : 랜덤한 32글자를 붙인다.
매개변수로 DTO 두개 이상 가능
필드 이름에 맞추어서 DTO 구분해 들어간다.
1. 글쓰기에 파일 업로드도 적용 해보기 (다중 파일?)
보드 서비스, 파일 서비스 두개?
보드DAO 파일DAO
https://offbyone.tistory.com/69
스프링프레임웍 ajax 파일업로드 - jQuery, FormData, jQuery Form Plugin 사용
이 글에서는 스프링 프레임웍 환경에서 ajax를 통한 파일 업로드 방법을 알아 보겠습니다. 서버와의 ajax 통신에는 jQuery를 사용하고 업로드를 위해서 FormData 객체를 사용하는 방법과 jQuery Form Plugin
offbyone.tistory.com
2. 에이작스리스트 무한휠에서 네비바 형식으로 변경
3. 보드테이블에 아이피주소 넣기
4. 비회원 댓글은 아이피번호 노출되도록?
5. 댓글 기능
6. '수정하기'는 '작성하기' 개선 후에 다시 만들기
https://jyh1536.tistory.com/63
Spring 개발 - 게시판 만들기(15) - 파일 다중 업로드 및 게시판 수정하기(파일 업로드)
본 내용은 혼자 공부하기 위하여 다른 포스트를 보면서 저에게 필요한 부분과 궁금했던 부분을 추가하여 게시하는 곳입니다. 궁금한 것에 대한 것은 모르는 것이 많겠지만 함께 알아보도록 노�
jyh1536.tistory.com
https://addio3305.tistory.com/83?category=772645
스프링(Spring) 개발 - (13) 파일 업로드 & 다운로드 (1/3)
이번글에서는 첨부파일 업&다운로드에 대해서 이야기 하려고 합니다. 웹에서 첨부파일은 상당히 문제가 많이 일어나는 부분이기도 합니다. 실제로 프로젝트중에서 첨부파일때문에 오픈이 지연
addio3305.tistory.com
'디지털 컨버전스 > Spring' 카테고리의 다른 글
[Spring Framework] 파일 다운로드 (0) | 2020.06.08 |
---|---|
[Spring Framwork] 파일 업로드 개수 (0) | 2020.06.05 |
[Spring Framework] 트랜젝션 처리 (0) | 2020.06.05 |
[Spring Framework] 트랜젝션 처리 (0) | 2020.06.04 |
[Spring Framework] 게시판 페이지 네비게이터 (0) | 2020.06.04 |