안녕하세요. 이번시간에는 java에 파일 업로드 기능을 등록하는 방법에대해서 간단하게 설명드리겠습니다.
참고로 이 게시글은 저의 기억력이 좋지 않아서 간략하게 작성되는 점 양해바랍니다.
* action-servlet.xml ( 개인마다 차이는 있지만 -servlet 으로 끝납니다 )
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="EUC-KR" /> <!-- 인코딩-->
<property name="maxUploadSize" value="10000000" /> <!-- 최대 사이즈-->
</bean>
* jsp
<form action="/fileUpload.do" enctype="multipart/form-data" method="post">
<input type="file" name="file" id="file">
<button type="submit">업로드</button>
</form>
여기서 저 enctype 부분은 필수입니다 !
* 라이브러리 추가
compile group: 'commons-fileupload', name: 'commons-fileupload', version:'1.3'
참고로 필자는 gradle 환경이므로 라이브러리는 저렇게 적용을 시켰습니다.
* 파일을 받을 경로 지정 ( Controller 부분 )
@RequestMapping("/fileUpload.do")
public ModelAndView mybatistest(HttpServletRequest request) throws IOException{
ModelAndView mav = new ModelAndView();
MultipartHttpServletRequest multi = (MultipartHttpServletRequest) request;
MultipartFile file = multi.getFile("fileNm");
String path="";
UUID randomeUUID = UUID.randomUUID();
if(file!=null){
System.out.println("파라미터명" + file.getName());
System.out.println("파일크기" + file.getSize());
System.out.println("파일 존재" + file.isEmpty());
System.out.println("오리지날 파일 이름" + file.getOriginalFilename());
path = "c:/upload/";
InputStream inputStream = null;
OutputStream outputStream = null;
String organizedfilePath="";
try {
if (file.getSize() > 0) {
inputStream = file.getInputStream();
File realUploadDir = new File(path);
if (!realUploadDir.exists()) {
realUploadDir.mkdirs();//폴더생성.
}
organizedfilePath = path + randomeUUID + "_" + file.getOriginalFilename();
System.out.println(organizedfilePath);//파일이 저장된경로 + 파일 명
outputStream = new FileOutputStream(organizedfilePath);
int readByte = 0;
byte[] buffer = new byte[8192];
while ((readByte = inputStream.read(buffer, 0, 8120)) != -1) {
outputStream.write(buffer, 0, readByte); //파일 생성 !
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
outputStream.close();
inputStream.close();
}
}
mav.setViewName("fileUpload");
return mav;
}
참고하셔서 한번 해보세요
'기타' 카테고리의 다른 글
리눅스 스케쥴링 crontab 설치 (0) | 2021.06.04 |
---|---|
MySQL - Insert 이후 바로 key값 사용하는 방법 (0) | 2021.05.21 |
카카오 맵 API 사용하여 행정구역 영역 설정하기 (0) | 2021.05.11 |
Client does not support authentication protocol requested by server; consider upgrading MySQL client 에러 해결 방법!! (0) | 2021.05.10 |
DB관리하기 쉬운 - DBeaver 설치하고 사용하기 (0) | 2021.05.10 |
댓글