728x90
반응형
https://turing0809.tistory.com/77
[back] java에서 MultipartFile 여러개 받기
text 파일 java에서 받기 < html > 전송 < java > @RequestMapping("/addTestFile") public void addTestFile(MultipartHttpServletRequest file) { Map fileMap = file.getFileMap(); Iterator itr = fileMap.entrySet().iterator(); MultipartFile myFile; while(it
turing0809.tistory.com
이 글에 이어서 작성..
파일을 하나만 받을 거라서 MultipartHttpServletRequest 객체의 getFile() 메소드를 사용했다.
getFile("file명") 함수의 리턴 타입은 MultipartFile로, form을 통해 보낸 단일 파일을 가져올 수 있다.
< html >
<form id="fileForm" name="fileForm" method="post" action="/test/addTestFile.do" enctype="multipart/form-data">
<input type="file" name="myFile">
<button>전송</button>
</form>
< java >
@RequestMapping("/addTestFile")
public void addTestFile(MultipartHttpServletRequest file) {
String rootPath = "C:/Users/User/Desktop/uploadFiles/";
File folder = new File(rootPath);
if(!folder.exists()) { // rootPath 에 해당하는 폴더가 없으면 신규 생성
folder.mkdirs();
}
// 실제 전송 file
MultipartFile myFile = file.getFile("myFile");
// rootPath + 파일명으로 해당 경로를 가리키는 파일객체 생성
File uploadFile = new File(rootPath + myFile.getOriginalFilename());
try {
myFile.transferTo(uploadFile); // 파일 복사(myFile파일을 --> uploadFile 파일객체로)
} catch (Exception e) {
e.printStackTrace();
}
}
실질적으로 파일을 복사하는 부분은 transferTo() <-- 여기다.
파일경로에 해당하는 객체를 생성하고, 그 경로로 전송한 파일을 객체로 받아 복사하고.
다른 코드도 들어가긴 했지만 핵심만 따지고 보면 단 두 줄의 코드로 파일 업로드가 된다니 싱기할 따름이다.
실제 업무 소스에서도 파일용 폴더를 따로 두고, rootPath 변수값을 조정하고 있다.
업로드 과정 정리 그림
728x90
반응형
'웹개발지식쌓기' 카테고리의 다른 글
[front] 크롬 인스펙터 HTTP/1.1 404 Not Found (0) | 2023.03.03 |
---|---|
[back] 이클립스 eXERD 컬럼명 관리 - 용어사전 사용 (0) | 2023.01.04 |
[back] java에서 MultipartFile 여러개 받기 (0) | 2022.12.12 |
[front] 자바스크립트 브라우저 차단 (0) | 2022.12.07 |
[back] Java JSON 2뎁스 이상 구조 만들기 (0) | 2022.11.30 |