스프링

 

pom.xml

<!-- 파일 업로드 드라이브
	servlet-context.xml 에서 CommonsMultipartResolver 파일 설정 필수
 -->
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>

<!-- 파일 업로드 썸네일 이미지 크기 조절 드라이브 -->
<!-- https://mvnrepository.com/artifact/org.imgscalr/imgscalr-lib -->
<dependency>
    <groupId>org.imgscalr</groupId>
    <artifactId>imgscalr-lib</artifactId>
    <version>4.2</version>
</dependency>

 

UploadPath class

public class UploadPath {

	public static String attach_path ="resources/uploads/";
	
	public static String path(HttpServletRequest request){	
		String uploadPath ="";
		
		try{
			String root_path =request.getServletContext().getRealPath("/");
			
			uploadPath =root_path+attach_path.replace('/', File.separatorChar);
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return uploadPath;
	}
	
	
}

 

Controller

@Controller
@RequestMapping(value="/upload")
public class UploadController {

	
	private static final Logger logger=LoggerFactory.getLogger(UploadController.class);
	
	
	private static final String JSP_PAGE ="/view/uploads"; 
	
	@RequestMapping(value="/uploadForm",  method=RequestMethod.GET)
	public String uploadForm(){
		
		return JSP_PAGE +"/upload";
	}
	
//업로드 버튼 =>업로드 완료 =>파일 정보가 file 에 저장	
	
	@RequestMapping(value="/uploadForm", method=RequestMethod.POST)
	public String upload(MultipartFile file,  RedirectAttributes rttr,
		HttpServletRequest request
			) throws Exception{
		
		logger.info("파일 이름 :" + file.getOriginalFilename());
		
		logger.info("파일 크기 :"+ file.getSize());
		logger.info("컨텐트 타입 : " + file.getContentType());
		
		
		String savedName =uploadFile(request, file.getOriginalFilename(), file.getBytes());
		
		rttr.addFlashAttribute("savedName", savedName);
		rttr.addFlashAttribute("realName", file.getOriginalFilename());
		return "redirect:uploadForm";

	}
	
	
	private String uploadFile (HttpServletRequest request, String originalName, byte[] fileData) throws Exception{
		
		UUID  uid =UUID.randomUUID();
		
		String savedName =uid.toString() +"_" +originalName;
		
		File target =new File(UploadPath.path(request),savedName);
		
		FileCopyUtils.copy(fileData, target);
		
		return savedName;
	}
	
	
		
}


 

HTML

		<div>
           		
 <h5>업로드할 파일을 선택해 주세요.</h5>
<form action="/upload/uploadForm" method="post" enctype="multipart/form-data" role='form1'>
           			
 <input type="file" name="file" class="form-control" id="fileName"> <br>
           		
<input type="submit" value="업로드" class="form-control" id="fileSubmit" >
           		
 </form>
	<c:if test="${not empty realName }">
 <h3>업로드 된 파일 명 : ${realName }</h3>
           		
 </c:if>	
           			
</div>

 

 

Script

<script>


$(document).ready(function(){
	
	
	$("#fileSubmit").click(function(event){
		
		event.preventDefault();
		
		var form=$("form[role='form1']");
		
	
	    var maxSize  = 7340032;    //7MB
	   
	    if($('#fileName').val().length < 1){
	    	alert("파일을 선택 해 주세요!");
	    	 return false;
	    }
	    
	    if ($('#fileName').val() != ""  ) { 
	        var size = document.getElementById("fileName").files[0].size;
	       
	         if(size > maxSize){
	               alert("첨부파일 사이즈는 7MB 이내로 등록 가능합니다.");
	               $('#fileName').val("");
	               $('#fileName').focus();
	                return false;
	            }
	    }

		
		form.submit();
			
		
	});


	
});



</script>

 

 

 

 

about author

PHRASE

Level 60  머나먼나라

생명의 자랑은 늘 신선하고 기운찬 점에 있다. 사람은 일생을 통하여 완성했다는 순간은 없는 것이다. -알랭

댓글 ( 4)

댓글 남기기

작성

스프링 목록    more