티스토리 뷰

Programming/Java

Spring MVC - 파일 업로드

파란크리스마스 2016. 12. 4. 16:52
728x90

Spring MVC Multipart Configuration (iot-servlet.xml 내용추가)

출처 : Spring MVC File Upload Example Tutorial - Spring MVC File Upload Example Tutorial – Single and Multiple Files
스프링(Spring) 파일 업로드(File Upload) :: 갱짱.study - 이갱짱 - Tistory

	<!-- ========================= Multipart Form-Data Resolver ========================= -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!--
		<property name="maxUploadSize">
			<value>10000000</value>
		</property>
		-->
	</bean>

FileUploadController.java

package com.iot.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileUploadController {

	@RequestMapping(value = "/file_upload_form.iot", method = RequestMethod.GET)
	public String file_upload_form(ModelMap modelMap) {
		return "/file_upload_form";
	}
	
	@RequestMapping(value = "/file_upload_save.iot", method = RequestMethod.POST)
	public String file_upload_save(@RequestParam("uploadfile") MultipartFile uploadfile, ModelMap modelMap) {

		OutputStream out = null;
		PrintWriter printWriter = null;

		try {
			// 파일명 얻기
			String fileName = uploadfile.getOriginalFilename();
			// 파일의 바이트 정보 얻기
			byte[] bytes = uploadfile.getBytes();
			// 파일의 저장 경로 얻기
			String uploadPath = getDestinationLocation() + fileName;
			
			// 파일 객체 생성
			File file = new File(uploadPath);
			// 상위 폴더 존재 여부 확인
			if (!file.getParentFile().exists()) {
				// 상위 폴더가 존재 하지 않는 경우 상위 폴더 생성
				file.getParentFile().mkdirs();
			}
			
			// 파일 아웃풋 스트림 생성
			out = new FileOutputStream(file);
			// 파일 아웃풋 스트림에 파일의 바이트 쓰기
			out.write(bytes);
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (printWriter != null) {
					printWriter.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return "/file_upload_form";
	}
	
	private String getDestinationLocation() {
		return "/업로드폴더/";
	}
}

file_upload_form.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="file_upload_save.iot" method="post" enctype="multipart/form-data">
		<fieldset>
			<table>
				<tr>
					<th>파일</th>
					<td><input type="file" name="uploadfile" required="required"></td>
				</tr>
				<tr>
					<td colspan="2">
						<input type="submit" value="작성">
						<input type="reset" value="취소">
					</td>
				</tr>
			</table>
		</fieldset>
	</form>
</body>
</html>

업로드 폴더 웹에 노출시키기

{tomcat_home}/conf/server.xml 내용 추가

<Context docBase="C:/업로드폴더" path="uploaddir" reloadable="true"/>

JQuery Ajax로 파일 업로드

출처 - Programming is Fun :: Spring MVC를 이용한 Ajax File upload

FileUploadController 내용 추가

	@RequestMapping(value = "/file_upload_form_ajax.iot", method = RequestMethod.GET)
	public String file_upload_form_ajax(ModelMap modelMap) {
		return "/file_upload_form_ajax";
	}

	@ResponseBody
	@RequestMapping(value = "/file_upload_save_ajax.iot", headers="Accept=*/*", method = RequestMethod.POST)
	public String file_upload_save_ajax(@RequestParam("uploadfile") MultipartFile uploadfile, ModelMap modelMap) {

		OutputStream out = null;

		try {
			String fileName = uploadfile.getOriginalFilename();
			byte[] bytes = uploadfile.getBytes();
			String uploadPath = getDestinationLocation() + fileName;// 저장경로
			
			File file = new File(uploadPath);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			
			out = new FileOutputStream(file);
			out.write(bytes);
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return "true";
	}

file_upload_form_ajax.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script  src="http://code.jquery.com/jquery-latest.min.js"></script>
<title>Insert title here</title>
<script type="text/javascript">
$( document ).ready(function() {
  $('#btn-upload').on('click', function () {
    console.log('btn-upload');
    var form = new FormData(document.getElementById('uploadForm'));
    $.ajax({
      url: "file_upload_save_ajax.iot",
      data: form,
      dataType: 'text',
      processData: false,
      contentType: false,
      type: 'POST',
      success: function (response) {
        console.log('success');
        console.log(response);
      },
      error: function (jqXHR) {
        console.log('error');
      }
    });
  });
});
</script>
</head>
<body>
	<form action="file_upload_save.iot" method="POST" id="uploadForm" enctype="multipart/form-data">
		<fieldset>
			<table>
				<tr>
					<th>파일</th>
					<td><input type="file" name="uploadfile" required="required"></td>
				</tr>
				<tr>
					<td colspan="2">
						<input type="submit" value="작성">
						<input type="reset" value="취소">
					</td>
				</tr>
			</table>
		</fieldset>
	</form>
	<span id="btn-upload">파일업로드AJAX</span>
</body>
</html>


댓글
300x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함