Spring - 파일 업로드

Programming/Java 2017.06.18 10:39 Posted by 파란크리스마스

출처 : [Spring, Tomcat] Could not parse multipart servlet request Unable to process parts as no multi-part configuration has been provided 해결 [소림사의 홍반장!]
[Apache/Tomcat] Context.xml 수정을 통한 문제 해결 - Cache, CSRF(Upload) [PostIT]
[Spring] Multipart를 사용한 페이지에서 Filter 적용하기 : 네이버 블로그

pom.xml

		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.2</version>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.5</version>
		</dependency>

MultipartFilter 적용(web.xml)

	<!-- MultipartFilter 적용 -->
	<filter>
		<filter-name>MultipartFilter</filter-name>
		<filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>MultipartFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

MultipartResolver 등록 (spring bean 등록)

	<!--  이미지 드래그 앤 드롭 업로드 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- max upload size in bytes -->
		<property name="maxUploadSize" value="209715200" /> <!-- 20MB -->
		<!-- max size of file in memory (in bytes) -->
		<property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->
	</bean>

allowCasualMultipartParsing 설정 (context.xml)

방법1 %TOMCAT%/conf/context.xml - Tomcat 전체 적용

<Context allowCasualMultipartParsing="true">

	<WatchedResource>WEB-INF/web.xml</WatchedResource>
	<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

	<!-- Default set of monitored resources. If one of these changes, the -->
	<!-- web application will be reloaded. -->
	<WatchedResource>WEB-INF/web.xml</WatchedResource>
	<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

	<!-- Uncomment this to disable session persistence across Tomcat restarts -->
	<!-- <Manager pathname="" /> -->

	<!-- 케시문제 해결 -->
	<Resources cachingAllowed="true" cacheMaxSize="100000"></Resources>

</Context>

방법2 WebContent\META-INF\context.xml - Eclipse 사용시 프로젝트에 적용

<?xml version="1.0" encoding="UTF-8"?>
<Context allowCasualMultipartParsing="true">
</Context>

form의 enctype

<form action="<c:url value="/insertCompleteForProblem.do"/>" method="post" enctype="multipart/form-data">
	    <tr>
	        <th scope="row">file</th>
	        <td><input type="file" size="20"  name="file1"></td>
	    </tr>

controller

	@RequestMapping(value = "/insertCompleteForProblem.do", method = RequestMethod.POST, headers = ("content-type=multipart/*"))
	public String joinComplete(
			@RequestParam("seq") int seq, 
			@RequestParam("quiz_name") String quiz_name, 
			@RequestParam("user_id") String user_id, 
			@RequestParam("price") String price,
			@RequestParam(value = "file1", required = false) MultipartFile mediaFile, 
			HttpServletRequest request, 
			ModelMap modelMap) throws Exception 
	{

		System.out.println("seq : " + seq);
		System.out.println("quiz_name : " + quiz_name);
		System.out.println("user_id : " + user_id);
		System.out.println("price : " + price);

		if (mediaFile.isEmpty() == false) {
			System.out.println("------------- file start -------------");
			System.out.println("name : " + mediaFile.getName());
			System.out.println("filename : " + mediaFile.getOriginalFilename());
			System.out.println("size : " + mediaFile.getSize());
			System.out.println("-------------- file end --------------\n");

			String originalFilename = mediaFile.getOriginalFilename(); // 파일명

			// 파일 확장자 추출
			String fileExt = FileUtils.getFileExt(originalFilename);

			UUID uuid = UUID.randomUUID();
			String targetFilename = uuid.toString() + "." + fileExt.toLowerCase();

			File file = new File(getDestinationLocation() + targetFilename);
			mediaFile.transferTo(file);
		}

		return "redirect:/main.do";
	}

	private String getDestinationLocation() {
		// return "/home/hosting_users/terecal/www/intel_images/";
		return "c:\\test\\";
	}


저작자 표시
신고

Spring 설정 pom.xml

Programming/Java 2017.06.05 19:50 Posted by 파란크리스마스

Spring 설정 pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>homepage</groupId>
	<artifactId>homepage</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<build>
		<sourceDirectory>src</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.5.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>3.0.0</version>
				<configuration>
					<warSourceDirectory>WebContent</warSourceDirectory>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<properties>
		<org.springframework-version>4.1.7.RELEASE</org.springframework-version>
		<org.springframework.security-version>4.0.1.RELEASE</org.springframework.security-version>
		<org.aspectj-version>1.8.1</org.aspectj-version>
		<org.slf4j-version>1.7.12</org.slf4j-version>
	</properties>
	<dependencies>
		<!-- Spring dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>

		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.2.2</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>

		<!-- spring framework jdbc 설정 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<!-- mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.0.6</version>
		</dependency>
		<!-- mybatis spring -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.0.2</version>
		</dependency>

		<!-- https://stackoverflow.com/questions/1074869/find-oracle-jdbc-driver-in-maven-repository -->
		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc</artifactId>
			<version>14</version>
			<scope>system</scope>
			<systemPath>${basedir}/libs/ojdbc6.jar</systemPath> <!-- must match file name -->
		</dependency>

	</dependencies>

</project>
저작자 표시
신고

java - mysql jdbc 연결

Programming/Java 2017.05.08 11:00 Posted by 파란크리스마스

출처 : 초보개발자 이야기. :: JAVA : JDBC를 사용하여 MySQL 과 연동하기 ...

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public class MySQLJDBCTest {
	
	public static void main(String [] args) throws Exception {
		
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		
		try {
			Class.forName("org.gjt.mm.mysql.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://bluexmas.tistory.com:3306/test_db", "test", "test");
			System.out.println("connection = " + conn);
			
			// 
			stmt = conn.prepareStatement("SHOW DATABASES");
			rs = stmt.executeQuery();
			
			//
			ResultSetMetaData rsmd = rs.getMetaData();
			int cols = rsmd.getColumnCount();
			System.out.printf("The query fetched %d columns\n",cols);
			System.out.println("These columns are: ");
			for (int i=1;i<=cols;i++) {
				String colName = rsmd.getColumnName(i);
				String colType = rsmd.getColumnTypeName(i);
				System.out.println(colName+" of type "+colType);
			}
			
			//
			while (rs.next()) {
				String str = rs.getNString(1);
				System.out.println(str);
			}
		} catch (SQLException sqex) {
			System.out.println("SQLException: " + sqex.getMessage());
			System.out.println("SQLState: " + sqex.getSQLState());
		} finally {
			if (rs != null) try { rs.close(); } catch (SQLException e) { }
			if (stmt != null) try { stmt.close(); } catch (SQLException e) { }
			if (conn != null) try { conn.close(); } catch (SQLException e) { }
		}
	}

}
저작자 표시
신고

Maven - Spring 설정

Programming/Java 2017.05.05 19:55 Posted by 파란크리스마스

Maven - Spring 설정

Properties 추가

[Properties]항목에서 [Create]버튼을 선택해서 아래와 같이 입력하고 [OK]버튼을 선택

Name : org.springframework-version
Value : 4.1.7.RELEASE

Dependencies 추가

groupId : org.springframework
artifactId : spring-context
version : ${org.springframework-version}

저작자 표시
신고

Maven 설치

Programming/Java 2017.05.05 18:15 Posted by 파란크리스마스

Maven 설치

출처 : MAVEN 설치 및 Eclipse 연동하기 - FREESTROKES' Develog - Tistory

Maven 다운로드

Maven 다운로드 사이트에서 최신 Maven 파일(apache-maven-3.5.0-bin.zip)을 다운받아 적당한 폴더에 압축을 푼다. 

환경설정

환경 변수 MAVEN_HOME 를 설정

Maven의 bin 폴더 Path에 추가

환경변수 path 항목에 구분자(;) 와 함께 추가 %MAVEN_HOME%\bin 추가

JDK 설치후 JAVA_HOME 설정

Maven 설치 확인

명령 프롬프트에서 mvn --version 실행

Eclipse Maven 설정

Maven 설정 변경 (옵션)

%MAVEN_HOME%\conf\settings.xml 파일을 C:\spring\maven 폴더에 복사

복사한 settings.xml 수정 - localRepository 주석을 제거하고 적당한 폴더 설정

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ${user.home}/.m2/repository
  -->
  <localRepository>C:/spring/maven/repository</localRepository>

eclipse - maven user settings

이클립스 프로젝트 Maven 연동

출처 : HunIT Blog :: Eclipse〃이클립스에 메이븐(Maven) 연동 및 환경설정


저작자 표시
신고

JsonConfig 사용

Programming/Java 2017.04.23 16:48 Posted by 파란크리스마스

JsonConfig 사용하기

출처 : 알팅스님의 개발 스토리 : Java Object(POJO) To JSON String

Mybatis XML

	<resultMap id="resultMapUserInfo" type="map">
		<result property="user_id" column="user_id" javaType="java.lang.String"/>
		<result property="email" column="email" javaType="java.lang.String"/>
		<result property="mobile" column="mobile" javaType="java.lang.String"/>
		<result property="name" column="name" javaType="java.lang.String"/>
		<result property="point" column="point" javaType="int"/>
		<result property="reg_date" column="reg_date" javaType="java.util.Date"/>
		<result property="service_start_date" column="service_start_date" javaType="java.util.Date"/>
		<result property="service_end_date" column="service_end_date" javaType="java.util.Date"/>
	</resultMap>

	<!-- listUser -->
	<select id="listUser" parameterType="map" resultMap="resultMapUserInfo">
		select a.*
		  FROM user_info a
		 WHERE a.delete_yn = 'N'
	</select>

Java

	JsonConfig jsonConfig = new JsonConfig();
	jsonConfig.registerJsonValueProcessor(java.util.Date.class, new JsonValueProcessor() {

		@Override
		public Object processArrayValue(Object value, JsonConfig jsonConfig) {
			
			java.util.Date[] dates = (java.util.Date[]) value;
			Long[] result = new Long[dates.length];
			for (int index = 0; index < dates.length; index++) {
				result[index] = dates[index].getTime();
			}
			return result;
		}

		@Override
		public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
			java.util.Date date = (java.util.Date) value;
			return date.getTime();
		}
	});
	
	List<Map<String, Object>> listUser = service.listUser(null);
	jsonObjet.put("listUser", JSONArray.fromObject(listUser, jsonConfig));
저작자 표시
신고

CKEditor 4.6

Programming/Java 2017.04.09 17:29 Posted by 파란크리스마스

CKEditor 4.6

출처 : CKEditor 4.6
CKEditor not working after opening jQuery UI Dialog - Stack Overflow

CKEditor - JQuery UI Dialog와 같이 사용하기

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="<c:url value="/resources/js/jquery-1.12.0.js"/>"></script>
<script type="text/javascript" src="<c:url value="/resources/js/jquery-ui.js"/>"></script>
<script type="text/javascript" src="<c:url value="/resources/ckeditor/ckeditor.js"/>"></script>
<link rel="stylesheet" href="<c:url value="/resources/css/jquery-ui.css"/>">
<title>JQuery Dialog</title>
<script type="text/javascript">
// CKEditor 기본 경로 설정 - config.js의 경로 설정
window.CKEDITOR_BASEPATH = '<c:url value="/resources/ckeditor"/>';
//window.parent.CKEDITOR.tools.callFunction('콜백의 식별 ID 값', '파일의 URL', '전송완료 메시지')

// CKEditor 제거 함수 - CKEditor 생성 되어 있는지 확인 후 제거
function DestryoCKEditorInstances(textarea_name) {
	if (CKEDITOR.instances[textarea_name])	{
		CKEDITOR.instances[textarea_name].destroy();
	}
}

function insertPopUpForSubject(){
	// 팝업 다이얼로그
	$("#tabb_subject_insert").dialog({
		position : {
			my : 'center center',
			at : 'center top'
		},
		width : 800,
		//height : 800,
		modal : true,
		open: function( event, ui ) {
			// 팝업창 열릴때 CKEditor 설정
			CKEDITOR.replace( 'example_subject_insert' , {
				extraPlugins: 'uploadimage,image2',
				uploadUrl: '<c:url value="/dragdrop/fileUpload/ckeditor2.do"/>',
				filebrowserImageUploadUrl: '<c:url value="/dragdrop/fileUpload/ckeditor.do"/>'
			});
		},
		close: function () {
			// 반듯이 팝업창 닫힐때 제거 되어함
			DestryoCKEditorInstances('example_subject_insert');
		}
	});
}
</script>
</head>
<body>

<button class="button button2" onclick="javascript:insertPopUpForSubject();">문제 입력1</button>

<div id="tabb_subject_insert"  title="문제 입력!"  style="display:none">
	<table align="center" width="90%" border="0" cellspacing="0" cellpadding="0">
	<tr>
		 <td>seq</td>
		 <td><input type="text" size="20" id="seq_subject_insert" ></td>
	</tr>
	<tr>
		 <td>보기</td>
		 <td>
			<textarea id="example_subject_insert" name="example_subject_insert" form="usrform">Enter text here...</textarea>
		 </td>
	</tr>
	</table>
	<center>
		<button class="button button5" onclick="javascript:insert_subject1_complete(1);">입력 완료(과목1)</button>
		<button class="button button5" onclick="javascript:cancle_insert();">취 소</button>
	</center>
</div>

</body>
</html>


저작자 표시
신고

Spring MVC - 네이버 로그인 처리

Programming/Java 2017.04.03 16:05 Posted by 파란크리스마스

Spring MVC - 네이버 로그인 처리

네이버 로그인 API를 이용해서 네이버 계정으로 로그인 처리를 Spring 프레임웍에서 사용 할 수 있도록 간단하게 NaverLoginController를 작성해보았습니다. 임시로 로그인 결과값을 가지고 와서 tbluser2 테이블의 abcd 계정의 1111 암호를 사용하는 사용자로 로그인 되도록 고정했습니다. (authentication-provider 사용자가 제어 하는 부분은 따로 찾아서 적용필요)

bluexmas-security.xml

alias의 authenticationManager 이름은 NaverLoginController 에서 속성으로 사용

	<security:authentication-manager alias="authenticationManager">
		<security:authentication-provider>

			<security:jdbc-user-service
				data-source-ref="dataSource"
				users-by-username-query="select user_id username, pass password, 1 as enabled from tbluser2 where user_id = ?"
				authorities-by-username-query="select user_id username, 'ROLE_USER' authority from tbluser2 where user_id = ?" />

		</security:authentication-provider>
	</security:authentication-manager>

NaverLogInController.java

package com.bluexmas.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.SecureRandom;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;

@Controller
public class NaverLogInController {
	
	private String naverClientId = "네이버API_Client_ID";
	
	private String naverClientSecret = "네이버API_Client_Secret";
	
	private String state = "";
	
	@Autowired
	@Qualifier("authenticationManager")
	protected AuthenticationManager authenticationManager;
	
	/**
	 * 네이버 로그인 요청
	 * 
	 * @param request
	 * @param uri
	 * @return
	 */
	@RequestMapping(value = "/naverLogin.do")
	public String makeNaverRequestStatement(
			HttpServletRequest request,
			@RequestParam(value = "uri", required = false) String uri) 
	{
		HashMap<String, String> naverUrl = this.makeRequestStatement(request, naverClientId);
		this.state = naverUrl.get("state");
		String returnUrl = request.getHeader("referer");
		
		return "redirect:" + naverUrl.get("url");
	}
	
	/**
	 * 네이버 로그인 요청에 대한 응답 처리
	 * 
	 * @param request
	 * @param response
	 * @param state
	 * @param code
	 * @param error
	 * @param error_description
	 * @return
	 */
	@RequestMapping(value = "/naverRequestKey.do")
	public String getNaverRequestKey(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam("state") String state, 
			@RequestParam(value = "code", required = false) String code, 
			@RequestParam(value = "error", required = false) String error, 
			@RequestParam(value = "error_description", required = false) String error_description) 
	{
		HttpSession session = request.getSession();
		
		System.out.print("state = " + this.state + "="+  state + "/code = " + code + "/error = " + error + "/error_description = " + error_description);
		
		if (state.equals(this.state)) {
			session.setAttribute("isLoged", true);
		} else {
			session.setAttribute("isLoged", false);
			//System.out.println("state key값 불일치. 인증에러");
			return "redirect:/index.html";
		}
		
		// 네이버에 token_type, access_token 요청
		HashMap<String, String> result1 = this.getRequestKey(request, state, code, naverClientId, naverClientSecret);
		
		//
		String access_token = result1.get("access_token");
		String refresh_token = result1.get("refresh_token");
		String token_type = result1.get("token_type");
		
		System.out.println("access_token = " + access_token + "," + refresh_token + "," + token_type);

		// 사용자 정보 조회 요청
		HashMap<String, Object> result2 = this.requestUserInfo(token_type, access_token);
		System.out.println("result=" + result2);

		String email = (String)result2.get("email");
		
		if (email==null) {
			System.out.println("email = " + email);
			session.setAttribute("isLoged", false);
			return "redirect:/index.html";
		}
		
		String user_id = (String)result2.get("email");
		
		// 수동 로그인(spring security manual login) 처리
		try {
			// 
			UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken("abcd", "1111");
			
			// Authenticate the user
			Authentication authentication = authenticationManager.authenticate(authRequest);
			SecurityContext securityContext = SecurityContextHolder.getContext();
			securityContext.setAuthentication(authentication);
		} catch (Exception e) {
			e.printStackTrace();
			SecurityContextHolder.getContext().setAuthentication(null);
		}
		
		//return "redirect:" + returnUrl;
		return "redirect:/index.html";
	}
	
	/**
	 * 호스트이름 반환
	 * 
	 * @param request
	 * @return
	 */
	public static String getHostname(HttpServletRequest request) {
		String port_str = (request.getServerPort()==80 ? "" : ":" + request.getServerPort());
		return "http://" + request.getServerName() + port_str + request.getContextPath();
	}
	
	/**
	 * state 값 생성
	 * 
	 * @return
	 */
	public String generateState() {
		SecureRandom random = new SecureRandom();
		return new BigInteger(130, random).toString(32);
	}
	
	/**
	 * 네이버 로그인 요청 (Redirect URL 생성)
	 * 
	 * 1. redirect 생성 - 네이버 로그인 요청 완료 후 응답 받는 url 생성
	 * 2. state 생성 - Ramdom 함수로 생성
	 * 3. 요청 URL 생성 반환
	 * 
	 * @param request
	 * @param clientId
	 * @return
	 */
	private HashMap<String, String> makeRequestStatement(HttpServletRequest request, String clientId) {
		//String redirectUri = "http://127.0.0.1:8080/naverRequestKey.cmx";
		String redirectUri = getHostname(request) + "/naverRequestKey.do";
		String state = generateState();
		String url = "https://nid.naver.com/oauth2.0/authorize?" + "response_type=code&client_id=" + clientId + "&redirect_uri=" + redirectUri + "&state=" + state;
		
		HashMap<String, String> naverUrl = new HashMap<String, String>();
		naverUrl.put("state", state);
		naverUrl.put("url", url);
		return naverUrl;
	}
	
	/**
	 * 네이버에 token_type, access_token 요청(로그인 성공 이후)
	 * 
	 * @param request
	 * @param state
	 * @param code
	 * @param clientId
	 * @param naverClientSecret
	 * @return
	 */
	private HashMap<String, String> getRequestKey(HttpServletRequest request, String state, String code, String clientId, String naverClientSecret) {
		String naverUrl = "https://nid.naver.com/oauth2.0/token?client_id=" + clientId + "&client_secret=" + naverClientSecret + "&grant_type=authorization_code" + "&state=" + state + "&code=" + code;
		String naverJsonKey = "";// null로 하니까 null이 json에 포함이 됨.
		HashMap<String, String> result = new HashMap<String, String>();

		try {
			HttpURLConnection conn = (HttpURLConnection) new URL(naverUrl).openConnection();
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String input;
			while ((input = reader.readLine()) != null) {
				naverJsonKey += input;
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		try {
			JSONParser parser = new JSONParser();
			JSONObject jsonObject = (JSONObject) parser.parse(naverJsonKey);
			
			result.put("access_token", (String) jsonObject.get("access_token"));
			result.put("refresh_token", (String) jsonObject.get("refresh_token"));
			result.put("token_type", (String) jsonObject.get("token_type"));
			
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 네이버에 로그인 사용자의 정보 요청
	 * 
	 * @param token_type
	 * @param access_token
	 * @return
	 */
	public HashMap<String, Object> requestUserInfo(String token_type, String access_token) {
		
		String url = "https://apis.naver.com/nidlogin/nid/getUserProfile.xml";
		String naverResult = "";
		try {
			HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Authorization", token_type + " " + access_token);
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String input;
			while ((input = reader.readLine()) != null) {
				naverResult += input;
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		HashMap<String, Object> result = new HashMap<String, Object>();

		try {
			InputSource is = new InputSource(new StringReader(naverResult));
			Document xml = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
			XPath xpath = XPathFactory.newInstance().newXPath();
			Node email = (Node) xpath.evaluate("//data/response/email", xml, XPathConstants.NODE);
			Node nickname = (Node) xpath.evaluate("//data/response/nickname", xml, XPathConstants.NODE);
			Node profile_image = (Node) xpath.evaluate("//data/response/profile_image", xml, XPathConstants.NODE);
			Node age = (Node) xpath.evaluate("//data/response/age", xml, XPathConstants.NODE);
			Node gender = (Node) xpath.evaluate("//data/response/gender", xml, XPathConstants.NODE);
			Node id = (Node) xpath.evaluate("//data/response/id", xml, XPathConstants.NODE);
			Node birthday = (Node) xpath.evaluate("//data/response/birthday", xml, XPathConstants.NODE);
			if (email!=null) result.put("email", email.getTextContent());
			if (nickname!=null) result.put("nickname", nickname.getTextContent());
			if (profile_image!=null) result.put("profile_image", profile_image.getTextContent());
			if (age!=null) result.put("age", age.getTextContent());
			if (gender!=null) result.put("gender", gender.getTextContent());
			if (id!=null) result.put("id", id.getTextContent());
			if (birthday!=null) result.put("birthday", birthday.getTextContent());

		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

}


저작자 표시
신고

Chart.js - Spring 연동

Programming/Java 2017.03.29 20:05 Posted by 파란크리스마스

Chart.js - Spring 연동

출처 : Chart.js - Spring 연동

JSONChartJS 클래스

package com.intel4.json;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.intel4.service.QuestionListService;
import com.intel4.util.BeanUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JSONChartJS extends JSONData {

	@Override
	public JSONObject getJSON(HttpServletRequest request, HttpServletResponse response) {

		String subcmd = request.getParameter("subcmd");
		JSONObject jobj_data = null;
		if (subcmd.equals("line")) {
			jobj_data = getAddData(request, response);
		}
		return jobj_data;
	}

	private JSONObject getAddData(HttpServletRequest request, HttpServletResponse response) {
		
		JSONArray datas = new JSONArray();
		
		JSONObject data1 = new JSONObject();
		data1.put("month", "1월");
		data1.put("pc", 100);
		data1.put("monitor", 80);
		datas.add(data1);
		JSONObject data2 = new JSONObject();
		data2.put("month", "2월");
		data2.put("pc", 80);
		data2.put("monitor", 70);
		datas.add(data2);
		JSONObject data3 = new JSONObject();
		data3.put("month", "3월");
		data3.put("pc", 70);
		data3.put("monitor", 60);
		datas.add(data3);
		JSONObject data4 = new JSONObject();
		data4.put("month", "4월");
		data4.put("pc", 90);
		data4.put("monitor", 100);
		datas.add(data4);
		JSONObject data5 = new JSONObject();
		data5.put("month", "5월");
		data5.put("pc", 40);
		data5.put("monitor", 110);
		datas.add(data5);
		
		JSONObject result = new JSONObject();
		result.put("datas", datas);
		
		return result;
	}
}

Line Chart

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!doctype html>
<html>

<head>
<title>Line Chart</title>
<script type="text/javascript" src="<c:url value="/resources/js/jquery-1.12.0.js"/>"></script>
<script type="text/javascript" src="<c:url value="/resources/chartjs/Chart.js"/>"></script>
<style>
canvas {
	-moz-user-select: none;
	-webkit-user-select: none;
	-ms-user-select: none;
}
</style>
</head>
<body>

<div style="width: 80%">
	<div>
		<canvas id="canvas" height="350" width="600"></canvas>
	</div>
</div>

<script>
var chartLabels = [];
var chartData1 = [];
var chartData2 = [];

var lineChartData = {
	labels : chartLabels,
	datasets : [ {
		label : "월별 PC 판매량",
		fillColor : "rgba(220,220,220,0.2)",
		strokeColor : "rgba(220,220,220,1)",
		pointColor : "rgba(220,220,220,1)",
		pointStrokeColor : "#fff",
		pointHighlightFill : "#fff",
		pointHighlightStroke : "rgba(220,220,220,1)",
		data : chartData1
	}, {
		label : "월별 모니터 판매량",
		fillColor : "rgba(151,187,205,0.2)",
		strokeColor : "rgba(151,187,205,1)",
		pointColor : "rgba(151,187,205,1)",
		pointStrokeColor : "#fff",
		pointHighlightFill : "#fff",
		pointHighlightStroke : "rgba(151,187,205,1)",
		data : chartData2
	} ]

}

function createChart() {
	var ctx = document.getElementById("canvas").getContext("2d");
	LineChartDemo = Chart.Line(ctx, {
		data : lineChartData,
		options : {
			scales : {
				yAxes : [ {
					ticks : {
						beginAtZero : true
					}
				} ]
			}
		}
	});
}

try {
	$.ajax({
		type : 'POST',
		url : "<c:url value="/json"/>",
		dataType : 'json',
		data : {
			cmd : 'chart',
			subcmd : 'line'
		},
		success : function(result) {

			$.each(result.datas, function(inx, obj) {
				chartLabels.push(obj.month);
				chartData1.push(obj.pc);
				chartData2.push(obj.monitor);

			});

			createChart();

		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {
			alert('There is an error : method(group)에 에러가 있습니다.');
		}
	});

} catch (e) {
	alert(e);
}
</script>
</body>
</html>

실행결과

Bar Chart

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>


<script type="text/javascript" src="<c:url value="/resources/js/jquery-1.12.0.js"/>"></script>
<script type="text/javascript" src="<c:url value="/resources/chartjs/Chart.js"/>"></script>
<style>
canvas{
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
}
</style>


<body>
 <div style="width:80%">
        <div>
            <canvas id="canvas" height="350" width="600"></canvas>
        </div>
    </div>
<script>
var chartLabels = [];
var chartData1 = [];
var chartData2 = [];


var lineChartData = {
    labels : chartLabels,
    datasets : [
        {
            label: "월별 PC 판매량",
            fillColor : "rgba(220,220,220,0.2)",
            strokeColor : "rgba(220,220,220,1)",
            pointColor : "rgba(220,220,220,1)",
            pointStrokeColor : "#fff",
            pointHighlightFill : "#fff",
            pointHighlightStroke : "rgba(220,220,220,1)",
            data : chartData1 ,
            backgroundColor: [
                "#FF6384",
                "#4BC0C0",
                "#FFCE56",
                "#E7E9ED",
                "#36A2EB"
            ]
        },
        {
            label: "월별 모니터 판매량",
            fillColor : "rgba(151,187,205,0.2)",
            strokeColor : "rgba(151,187,205,1)",
            pointColor : "rgba(151,187,205,1)",
            pointStrokeColor : "#fff",
            pointHighlightFill : "#fff",
            pointHighlightStroke : "rgba(151,187,205,1)",
            data : chartData2,
            backgroundColor: [
                "#FF6384",
                "#4BC0C0",
                "#FFCE56",
                "#E7E9ED",
                "#36A2EB"
            ]
        }
    ]
 
}

function createChart(){
    var ctx = document.getElementById("canvas").getContext("2d");
    new Chart(ctx, {
        type: 'horizontalBar',
    	data: lineChartData,
    	options: {
            scales: {
            	xAxes: [{
                    ticks: {
                        beginAtZero:true
                    }
                }]
            }
        }
    });
}

try {
	$.ajax({
		type : 'POST',
		url : "<c:url value="/json"/>",
		dataType : 'json',
		data : {
			cmd : 'chart',
			subcmd : 'line'
		},
		success : function(result) {
		
			    $.each(result.datas, function(inx, obj) {
			        chartLabels.push(obj.month);
			        chartData1.push(obj.pc);
			        chartData2.push(obj.monitor);
			         
			    });
			     
			    createChart();
			
		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {
			alert('There is an error : method(group)에 에러가 있습니다.');
		}
	});

} catch (e) {
	alert(e);
}

 
</script>

</body>

</html>

실행결과

Pie Chart

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!doctype html>
<html>

<head>
    <title>Pie Chart</title>
    <script type="text/javascript" src="<c:url value="/resources/js/jquery-1.12.0.js"/>"></script>
    <script type="text/javascript" src="<c:url value="/resources/chartjs/Chart.js"/>"></script>
    <style>
    canvas{
        -moz-user-select: none;
        -webkit-user-select: none;
        -ms-user-select: none;
    }
    </style>
</head>

<body>
 <div style="width:80%">
        <div>
            <canvas id="canvas" height="350" width="600"></canvas>
        </div>
    </div>
<script>
var chartLabels = [];
var chartData1 = [];
var chartData2 = [];


var PieChartData = {
    labels : chartLabels,
    datasets : [
        {
            label: "월별 PC 판매량",
            fillColor : "rgba(220,220,220,0.2)",
            strokeColor : "rgba(220,220,220,1)",
            pointColor : "rgba(220,220,220,1)",
            pointStrokeColor : "#fff",
            pointHighlightFill : "#fff",
            pointHighlightStroke : "rgba(220,220,220,1)",
            data : chartData1 ,
            backgroundColor: [
                "#FF6384",
                "#4BC0C0",
                "#FFCE56",
                "#E7E9ED",
                "#36A2EB"
            ]
        }
        
        /*,
        {
            label: "월별 모니터 판매량",
            fillColor : "rgba(151,187,205,0.2)",
            strokeColor : "rgba(151,187,205,1)",
            pointColor : "rgba(151,187,205,1)",
            pointStrokeColor : "#aff",
            pointHighlightFill : "#aff",
            pointHighlightStroke : "rgba(151,187,205,1)",
            data : chartData2,
            backgroundColor: [
                "#FF6384",
                "#4BC0C0",
                "#FFCE56",
                "#E7E9ED",
                "#36A2EB"
            ]
        }
        */
    ]
 
}
 
function createChart(){
    var ctx = document.getElementById("canvas").getContext("2d");
    new Chart(ctx, {
        type: 'pie',
    	data: PieChartData,
    	
        options: {
            responsive: true
        }
    });
}

try {
	$.ajax({
		type : 'POST',
		url : "<c:url value="/json"/>",
		dataType : 'json',
		data : {
			cmd : 'chart',
			subcmd : 'line'
		},
		success : function(result) {
		
			    $.each(result.datas, function(inx, obj) {
			        chartLabels.push(obj.month);
			        chartData1.push(obj.pc);
			        chartData2.push(obj.monitor);
			         
			    });
			     
			    createChart();
			
		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {
			alert('There is an error : method(group)에 에러가 있습니다.');
		}
	});

} catch (e) {
	alert(e);
}

 
</script>

</body>

</html>

실행결과

저작자 표시
신고

Spring MVC - Form 데이터 전달

Programming/Java 2017.03.26 19:51 Posted by 파란크리스마스

기본 Form 데이터 전달

기본 Form 데이터 전달 JSP - /sample/form1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>
<head>
<body>

<form action="<c:url value="/form/form1.do"/>" method="get">
	<input type="text" name="user_id">
	<input type="password" name="password">
	<input type="submit">
</form>

</body>
</html>

기본 Form 데이터 전달 Controller

@Controller
public class FormController {
	
	@RequestMapping(value = "/form/form1.do", method = RequestMethod.GET)
	public String form1(
			@RequestParam("user_id") String user_id, 
			@RequestParam("password") String password,
			ModelMap modelMap) throws Exception 
	{
		System.out.println("user_id = " + user_id + "/" + password);
		return "redirect:/sample/form1.jsp";
	}

파일 업로드 Form 데이터 전달

파일 업로드 Form 데이터 전달 JSP - /sample/form2.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>
<head>
<body>

<form action="<c:url value="/form/form2.do"/>" method="post" enctype="multipart/form-data">
	<input type="text" name="title"><br/>
	<input type="file" name="file1"><br/>
	<input type="file" name="file2"><br/>
	<input type="submit">
</form>

</body>
</html>

파일 업로드 Form 데이터 전달 Controller

@Controller
public class FormController {
	
	@RequestMapping(value = "/form/form2.do", method = RequestMethod.POST)
	public String form2(
			@RequestParam("title") String title, 
			@RequestParam("file1") MultipartFile file1, 
			@RequestParam("file2") MultipartFile file2, 
			ModelMap modelMap) 
	{
		System.out.println("title = " + title);
		
		String uuid_filename1 = fileWrite(file1);
		String uuid_filename2 = fileWrite(file2);
		
		System.out.println(uuid_filename1 + "/" + uuid_filename2);
		
		return "redirect:/sample/form2.jsp";
	}
	
	// 파일 저장 메소드
	private String fileWrite(MultipartFile uploadfile) {
		OutputStream out = null;
		String targetFilename = null;
		try {
			String filePath = "C:/test"; // 설정파일로 뺀다.
			
			// 파일명 얻기
			String fileName = uploadfile.getOriginalFilename();
			
			// 파일의 바이트 정보 얻기
			byte[] bytes = uploadfile.getBytes();
	
			String originalFilename = uploadfile.getOriginalFilename(); // 파일명
			
			// 파일 확장자 추출
			String fileExt = FileUtils.getFileExt(originalFilename);
	
			UUID uuid = UUID.randomUUID();
			targetFilename = uuid.toString() + "." + fileExt.toLowerCase();
	
			String fileFullPath = filePath + "/" + targetFilename; // 파일 전체 경로
			
			// 파일 객체 생성
			File file = new File(fileFullPath);
			// 상위 폴더 존재 여부 확인
			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 targetFilename;
	}
}
저작자 표시
신고

POI 라이브러리 사용 Excel Loader 구현

Programming/Java 2017.02.28 22:18 Posted by 파란크리스마스

ExcelUtils

package com.intel4.poi;

import java.io.IOException;
import java.io.InputStream;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelUtils {
	
	// 엑셀로드
	public static Workbook loalDocument(String filename,InputStream is) throws IOException {
		if (filename.endsWith(".xlsx")) {
			return new XSSFWorkbook(is);
		}
		else   if (filename.endsWith("xls")) {
			return new HSSFWorkbook(is);
		}
		else {
			throw new IllegalArgumentException("Unsupported extension for resource [" + filename + "]");
		}
	}
	
	// 문자열 반환
	public static String getStringValue(Row row, int col) {
		
		if (row == null) return null;
		if (row.getCell(col) == null) return null;
		
		String value = "";
		if (row.getCell(col).getCellType()==Cell.CELL_TYPE_NUMERIC) {
			double doubleValue = row.getCell(col).getNumericCellValue();
			if ((doubleValue == Math.floor(doubleValue)) && !Double.isInfinite(doubleValue)) {
				value = String.valueOf((int)row.getCell(col).getNumericCellValue());
			} else {
				value = String.valueOf(row.getCell(col).getNumericCellValue());
			}
			//System.out.println("doubleValue = " + doubleValue + "/" + value);
		} else if (row.getCell(col).getCellType()==Cell.CELL_TYPE_STRING) {
			try {
				value = row.getCell(col).getStringCellValue();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return value;
	}
	
	// int 값 반환
	public static int getIntegerValue(Row row, int col) {
		
		if (row == null) return 0;
		if (row.getCell(col) == null) return 0;
		
		int value = 0;
		if (row.getCell(col).getCellType()==Cell.CELL_TYPE_NUMERIC) {
			double doubleValue = row.getCell(col).getNumericCellValue();
			if ((doubleValue == Math.floor(doubleValue)) && !Double.isInfinite(doubleValue)) {
				value = (int)row.getCell(col).getNumericCellValue();
			} else {
				value = (int)row.getCell(col).getNumericCellValue();
			}
			//System.out.println("doubleValue = " + doubleValue + "/" + value);
		} else if (row.getCell(col).getCellType()==Cell.CELL_TYPE_STRING) {
			try {
				String stringValue = row.getCell(col).getStringCellValue();
				if (stringValue==null || stringValue.trim().length()==0 || !isNumeric(stringValue)) return 0;
				value = Integer.parseInt(row.getCell(col).getStringCellValue());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return value;
	}
	
	// 숫자여부 판단
	public static boolean isNumeric(String str) {
	  return str.matches("-?\\d+(\\.\\d+)?");  //match a number with optional '-' and decimal.
	}

}

ExcelLoader

package com.intel4.poi;

import java.io.File;
import java.io.FileInputStream;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

public class ExcelLoader {
	
	public static void main(String[] args) {
		ExcelLoader loader = new ExcelLoader();
		loader.load("WebContent\\sample.xlsx");
	}
	
	public void load(String filename) {
		int start_row = 1;
		
		FileInputStream inputStream = null;
		try {
			inputStream = new FileInputStream(new File(filename));
			Workbook workbook = ExcelUtils.loalDocument(filename, inputStream);
			
			// Excel 시트
			Sheet sheet = workbook.getSheetAt(0);
			
			// 해당 시트의 마지막 Row까지 반복
			for (int row_index=start_row; row_index<=sheet.getLastRowNum(); row_index++) {
				// Excel Row
				Row row = sheet.getRow(row_index);
				// row가 null인 경우 다음 row로...
				if (row == null) continue;
				
				int basic_seq = ExcelUtils.getIntegerValue(row, 0);
				int seq = ExcelUtils.getIntegerValue(row, 1);
				int problem = ExcelUtils.getIntegerValue(row, 2);
				String answer = ExcelUtils.getStringValue(row, 3);
				int hint  = ExcelUtils.getIntegerValue(row, 4);
				String subject1 = ExcelUtils.getStringValue(row, 5);
				String subject2 = ExcelUtils.getStringValue(row, 6);
				int level = ExcelUtils.getIntegerValue(row, 7);
				
				System.out.println(basic_seq + "/" + seq + "/" + problem +"/"+ answer + "/" + hint + "/" + subject1 + "/" + subject2 + "/" +  level);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (inputStream!=null) {
				try {
					inputStream.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

	}

}
저작자 표시
신고

Spring - Drag & Drop 파일 업로드

Programming/Java 2017.02.26 18:42 Posted by 파란크리스마스

Spring - Drag & Drop 파일 업로드

출처 : Husk's repository :: 드래그 앤 드롭 파일 업로드 스프링 예제

관련 라이브러리 추가

commons-io-2.4.jar
commons-fileupload-1.3.jar

WebContent\WEB-INF\iot-servlet.xml

	<!-- ========================= Multipart Form-Data Resolver ========================= -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- max upload size in bytes -->
		<property name="maxUploadSize" value="20971520" /> <!-- 20MB -->
		<!-- max size of file in memory (in bytes) -->
		<property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->
	</bean>

업로드 jsp (WebContent\WEB-INF\jsp\dragdrop\fileUpload.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
    <head>
        <title>Test</title>
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.js"></script>
        <style>
            .dragAndDropDiv {
                border: 2px dashed #92AAB0;
                width: 650px;
                height: 200px;
                color: #92AAB0;
                text-align: center;
                vertical-align: middle;
                padding: 10px 0px 10px 10px;
                font-size:200%;
                display: table-cell;
            }
            .progressBar {
                width: 200px;
                height: 22px;
                border: 1px solid #ddd;
                border-radius: 5px; 
                overflow: hidden;
                display:inline-block;
                margin:0px 10px 5px 5px;
                vertical-align:top;
            }
              
            .progressBar div {
                height: 100%;
                color: #fff;
                text-align: right;
                line-height: 22px; /* same as #progressBar height if we want text middle aligned */
                width: 0;
                background-color: #0ba1b5; border-radius: 3px; 
            }
            .statusbar{
                border-top:1px solid #A9CCD1;
                min-height:25px;
                width:99%;
                padding:10px 10px 0px 10px;
                vertical-align:top;
            }
            .statusbar:nth-child(odd){
                background:#EBEFF0;
            }
            .filename{
                display:inline-block;
                vertical-align:top;
                width:250px;
            }
            .filesize{
                display:inline-block;
                vertical-align:top;
                color:#30693D;
                width:100px;
                margin-left:10px;
                margin-right:5px;
            }
            .abort{
                background-color:#A8352F;
                -moz-border-radius:4px;
                -webkit-border-radius:4px;
                border-radius:4px;display:inline-block;
                color:#fff;
                font-family:arial;font-size:13px;font-weight:normal;
                padding:4px 15px;
                cursor:pointer;
                vertical-align:top
            }
        </style>
        <script type="text/javascript">
            $(document).ready(function(){
                var objDragAndDrop = $(".dragAndDropDiv");
                 
                $(document).on("dragenter",".dragAndDropDiv",function(e){
                    e.stopPropagation();
                    e.preventDefault();
                    $(this).css('border', '2px solid #0B85A1');
                });
                $(document).on("dragover",".dragAndDropDiv",function(e){
                    e.stopPropagation();
                    e.preventDefault();
                });
                $(document).on("drop",".dragAndDropDiv",function(e){
                     
                    $(this).css('border', '2px dotted #0B85A1');
                    e.preventDefault();
                    var files = e.originalEvent.dataTransfer.files;
                 
                    handleFileUpload(files,objDragAndDrop);
                });
                 
                $(document).on('dragenter', function (e){
                    e.stopPropagation();
                    e.preventDefault();
                });
                $(document).on('dragover', function (e){
                  e.stopPropagation();
                  e.preventDefault();
                  objDragAndDrop.css('border', '2px dotted #0B85A1');
                });
                $(document).on('drop', function (e){
                    e.stopPropagation();
                    e.preventDefault();
                });
                 
                function handleFileUpload(files,obj)
                {
                   for (var i = 0; i < files.length; i++) 
                   {
                        var fd = new FormData();
                        fd.append('file', files[i]);
                  
                        var status = new createStatusbar(obj); //Using this we can set progress.
                        status.setFileNameSize(files[i].name,files[i].size);
                        sendFileToServer(fd,status);
                  
                   }
                }
                 
                var rowCount=0;
                function createStatusbar(obj){
                         
                    rowCount++;
                    var row="odd";
                    if(rowCount %2 ==0) row ="even";
                    this.statusbar = $("<div class='statusbar "+row+"'></div>");
                    this.filename = $("<div class='filename'></div>").appendTo(this.statusbar);
                    this.size = $("<div class='filesize'></div>").appendTo(this.statusbar);
                    this.progressBar = $("<div class='progressBar'><div></div></div>").appendTo(this.statusbar);
                    this.abort = $("<div class='abort'>중지</div>").appendTo(this.statusbar);
                     
                    obj.after(this.statusbar);
                  
                    this.setFileNameSize = function(name,size){
                        var sizeStr="";
                        var sizeKB = size/1024;
                        if(parseInt(sizeKB) > 1024){
                            var sizeMB = sizeKB/1024;
                            sizeStr = sizeMB.toFixed(2)+" MB";
                        }else{
                            sizeStr = sizeKB.toFixed(2)+" KB";
                        }
                  
                        this.filename.html(name);
                        this.size.html(sizeStr);
                    }
                     
                    this.setProgress = function(progress){       
                        var progressBarWidth =progress*this.progressBar.width()/ 100;  
                        this.progressBar.find('div').animate({ width: progressBarWidth }, 10).html(progress + "% ");
                        if(parseInt(progress) >= 100)
                        {
                            this.abort.hide();
                        }
                    }
                     
                    this.setAbort = function(jqxhr){
                        var sb = this.statusbar;
                        this.abort.click(function()
                        {
                            jqxhr.abort();
                            sb.hide();
                        });
                    }
                }
                 
                function sendFileToServer(formData,status)
                {
                    var uploadURL = "<c:url value="/dragdrop/fileUpload/post.iot"/>"; //Upload URL
                    var extraData ={}; //Extra Data.
                    var jqXHR=$.ajax({
                            xhr: function() {
                            var xhrobj = $.ajaxSettings.xhr();
                            if (xhrobj.upload) {
                                    xhrobj.upload.addEventListener('progress', function(event) {
                                        var percent = 0;
                                        var position = event.loaded || event.position;
                                        var total = event.total;
                                        if (event.lengthComputable) {
                                            percent = Math.ceil(position / total * 100);
                                        }
                                        //Set progress
                                        status.setProgress(percent);
                                    }, false);
                                }
                            return xhrobj;
                        },
                        url: uploadURL,
                        type: "POST",
                        contentType:false,
                        processData: false,
                        cache: false,
                        data: formData,
                        success: function(data){
                            status.setProgress(100);
                  
                            //$("#status1").append("File upload Done<br>");           
                        }
                    }); 
                  
                    status.setAbort(jqXHR);
                }
                 
            });
        </script>
    </head>
     
    <body>
        <div id="fileUpload" class="dragAndDropDiv">Drag & Drop Files Here</div>
    </body>
</html>

Controller

package com.iot.controller;

import java.io.File;
import java.util.Iterator;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * Handles requests for the application home page.
 */

@Controller
public class FileUploadDragDropController {

	@RequestMapping(value = "/dragdrop/fileUpload.iot", method = RequestMethod.GET)
	public String dragAndDrop(Model model) {
		return "/dragdrop/fileUpload";
	}

	@RequestMapping(value = "/dragdrop/fileUpload/post.iot") // ajax에서 호출하는 부분
	@ResponseBody
	public String upload(MultipartHttpServletRequest multipartRequest) { // Multipart로
																																				// 받는다.

		Iterator<String> itr = multipartRequest.getFileNames();

		String filePath = "C:/test"; // 설정파일로 뺀다.

		while (itr.hasNext()) { // 받은 파일들을 모두 돌린다.

			/*
			 * 기존 주석처리 MultipartFile mpf = multipartRequest.getFile(itr.next());
			 * String originFileName = mpf.getOriginalFilename(); System.out.println(
			 * "FILE_INFO: "+originFileName); //받은 파일 리스트 출력'
			 */

			MultipartFile mpf = multipartRequest.getFile(itr.next());

			String originalFilename = mpf.getOriginalFilename(); // 파일명

			String fileFullPath = filePath + "/" + originalFilename; // 파일 전체 경로

			try {
				// 파일 저장
				mpf.transferTo(new File(fileFullPath)); // 파일저장 실제로는 service에서 처리

				System.out.println("originalFilename => " + originalFilename);
				System.out.println("fileFullPath => " + fileFullPath);

			} catch (Exception e) {
				System.out.println("postTempFile_ERROR======>" + fileFullPath);
				e.printStackTrace();
			}

		}

		return "success";
	}

}

업로드된 폴더 웹에서 접근하기

Tomcat 설정파일 server.xml에 <Context docBase="C:/test" path="/test" reloadable="true"/> 를 Host 테그 전에 추가

        <Context docBase="C:/test" path="/test" reloadable="true"/>
      </Host>
    </Engine>
  </Service>
</Server>

Spring - Drag & Drop 파일 업로드 (img_type, img_id 속성 추가)

한 페이지내에서 여러개의 파일 업로드를 구현하기 위해서 img_type, img_id 속성을 추가해서 여러개의 업로드가 발생하더라고 구분 할 수 있게 구현

html 페이지

<div class="dragAndDropDiv" img_type="uploadarea" img_id="1">
<div class="dragAndDropDiv" img_type="uploadarea" img_id="2">

파일 올려진 경우 이벤트에서 img_type, img_id 속성 가져오기 - javascript

	$(document).on("drop",".dragAndDropDiv",function(e){
		$(this).css('border', '2px dotted #0B85A1');
		e.preventDefault();
		var files = e.originalEvent.dataTransfer.files;
		
		// img_type, img_id 속성 가져오기
		var img_type = $(e.target).attr('img_type');
		var img_id = $(e.target).attr('img_id');
		
		handleFileUpload(img_type, img_id, files,objDragAndDrop);
	});

FormData 구성 img_type, img_id 포함 - javascript

	function handleFileUpload(img_type, img_id, files,obj) {
		for (var i = 0; i < files.length; i++) {
			var fd = new FormData();
			fd.append('img_type', img_type);
			fd.append('img_id', img_id);
			fd.append('file', files[i]);
			
			var status = undefined;
			//var status = new createStatusbar(obj); //Using this we can set progress.
			//status.setFileNameSize(files[i].name,files[i].size);
			sendFileToServer(fd,status);
		}
	}

업로드 완료 처리 - javascript

img_type이 request인 경우 img테그의 src 속성 값 변경 처리

function sendFileToServer(formData,status) {
	var uploadURL = "<c:url value="/dragdrop/fileUpload/post.do"/>"; //Upload URL

... 생략 ...

		data: formData,
		success: function(data) { // 업로드가 완료되면 호출되는 메소드
			if (status != undefined) {
				status.setProgress(100);
			}
			
			// 
			console.log('img_type = ' + data.img_type);
			console.log('img_id = ' + data.img_id);
			$.each(data.files, function(index, file) {
				console.log('filename = ' + file);
				
				if (data.img_type=='request') {
					var targetObj = $(".dragAndDropDiv[img_type='"+data.img_type+"'][img_id='"+data.img_id+"']");
					targetObj.attr('src', '/test/' + file);
					targetObj.attr('uuid', file);
				}
			});
		}
	});

javascript 전체

$(document).ready(function() {
	
	var objDragAndDrop = $(".dragAndDropDiv");
	   
	$(document).on("dragenter",".dragAndDropDiv",function(e){
		e.stopPropagation();
		e.preventDefault();
		$(this).css('border', '2px solid #0B85A1');
	});
	$(document).on("dragover",".dragAndDropDiv",function(e){
		e.stopPropagation();
		e.preventDefault();
	});
	$(document).on("drop",".dragAndDropDiv",function(e){
		$(this).css('border', '2px dotted #0B85A1');
		e.preventDefault();
		var files = e.originalEvent.dataTransfer.files;
		
		// img_type, img_id 속성 가져오기
		var img_type = $(e.target).attr('img_type');
		var img_id = $(e.target).attr('img_id');
		
		handleFileUpload(img_type, img_id, files,objDragAndDrop);
	});
	$(document).on('dragenter', function (e){
		e.stopPropagation();
		e.preventDefault();
	});
	$(document).on('dragover', function (e){
		e.stopPropagation();
		e.preventDefault();
		objDragAndDrop.css('border', '2px dotted #0B85A1');
	});
	$(document).on('drop', function (e){
		e.stopPropagation();
		e.preventDefault();
	});
	  
	function handleFileUpload(img_type, img_id, files,obj) {
		for (var i = 0; i < files.length; i++) {
			var fd = new FormData();
			fd.append('img_type', img_type);
			fd.append('img_id', img_id);
			fd.append('file', files[i]);
			
			var status = undefined;
			//var status = new createStatusbar(obj); //Using this we can set progress.
			//status.setFileNameSize(files[i].name,files[i].size);
			sendFileToServer(fd,status);
		}
	}
	  
	var rowCount=0;
	function createStatusbar(obj){
		
		rowCount++;
		var row="odd";
		if(rowCount %2 ==0) row ="even";
		this.statusbar = $("<div class='statusbar "+row+"'></div>");
		this.filename = $("<div class='filename'></div>").appendTo(this.statusbar);
		this.size = $("<div class='filesize'></div>").appendTo(this.statusbar);
		this.progressBar = $("<div class='progressBar'><div></div></div>").appendTo(this.statusbar);
		this.abort = $("<div class='abort'>중지</div>").appendTo(this.statusbar);
		
		obj.after(this.statusbar);
		
		this.setFileNameSize = function(name,size){
			var sizeStr="";
			var sizeKB = size/1024;
			if(parseInt(sizeKB) > 1024) {
				var sizeMB = sizeKB/1024;
				sizeStr = sizeMB.toFixed(2)+" MB";
			} else {
				sizeStr = sizeKB.toFixed(2)+" KB";
			}
			
			this.filename.html(name);
			this.size.html(sizeStr);
		}
		  
		this.setProgress = function(progress){      
			var progressBarWidth =progress*this.progressBar.width()/ 100; 
			this.progressBar.find('div').animate({ width: progressBarWidth }, 10).html(progress + "% ");
			if(parseInt(progress) >= 100) {
				this.abort.hide();
			}
		}
		  
		this.setAbort = function(jqxhr){
			var sb = this.statusbar;
			this.abort.click(function() {
				jqxhr.abort();
				sb.hide();
			});
		}
	}
	  
	function sendFileToServer(formData,status) {
		var uploadURL = "<c:url value="/dragdrop/fileUpload/post.do"/>"; //Upload URL
		var extraData ={}; //Extra Data.
		var jqXHR=$.ajax({
				xhr: function() {
				var xhrobj = $.ajaxSettings.xhr();
				if (xhrobj.upload) {
					xhrobj.upload.addEventListener('progress', function(event) {
						var percent = 0;
						var position = event.loaded || event.position;
						var total = event.total;
						if (event.lengthComputable) {
							percent = Math.ceil(position / total * 100);
						}
						//Set progress
						if (status != undefined) {
							status.setProgress(percent);
						}
					}, false);
				}
				return xhrobj;
			},
			url: uploadURL,
			type: "POST",
			dataType : 'json',
			contentType:false,
			processData: false,
			cache: false,
			data: formData,
			success: function(data) { // 업로드가 완료되면 호출되는 메소드
				if (status != undefined) {
					status.setProgress(100);
				}
				
				// 
				console.log('img_type = ' + data.img_type);
				console.log('img_id = ' + data.img_id);
				$.each(data.files, function(index, file) {
					console.log('filename = ' + file);
					
					if (data.img_type=='request') {
						var targetObj = $(".dragAndDropDiv[img_type='"+data.img_type+"'][img_id='"+data.img_id+"']");
						targetObj.attr('src', '/test/' + file);
						targetObj.attr('uuid', file);
					} else {
						var uploadTbody = $('#uploadTbody');
						var row = $('<span style="display : block;"></span>');
						row.text(file);
						uploadTbody.append(row);
						
						// 배열 초기화
						var uploadFilenames = new Array(9);
						for (i=0; i<uploadFilenames.length; i++) {
							uploadFilenames[i] = '';
						}
						var t_fileList = $('#uploadTbody>span');
						
						/*
						for (i=1; i<=t_fileList.length; i++) {
							var file_value = $('#uploadTbody>span:nth-child('+i+')');
							console.log(i + '/' + file_value.text());
							uploadFilenames[i-1] = file_value.text();
						}
						*/
						
						console.log(t_fileList.length);
						$.each( t_fileList, function( key, value ) {
							console.log( key + ": " + $(value).text() );
							uploadFilenames[key] = $(value).text();
						});
						
						console.log(uploadFilenames[0]);
						console.log(uploadFilenames[1]);
						console.log(uploadFilenames[2]);
						console.log(uploadFilenames[3]);
					}
				});
			
				//$("#status1").append("File upload Done<br>");          
			}
		});
		
		if (status != undefined) {
			status.setAbort(jqXHR);
		}
	}
});

업로드 메소드

	@RequestMapping(value = "/dragdrop/fileUpload/post.do") // ajax에서 호출하는 부분
	@ResponseBody
	public String upload(
			@RequestParam(value = "img_type", required = false, defaultValue = "") String img_type, 
			@RequestParam(value = "img_id", required = false, defaultValue = "-1") int img_id, 
			MultipartHttpServletRequest multipartRequest) // Multipart로 받는다.
	{ 

		System.out.println("img_type = " + img_type + "/img_id = " + img_id);

		Iterator<String> itr = multipartRequest.getFileNames();

		String filePath = "C:/test"; // 설정파일로 뺀다.
		String targetFilename = "";
		
		JSONArray filenames = new JSONArray();

		while (itr.hasNext()) { // 받은 파일들을 모두 돌린다.

			/*
			 * 기존 주석처리 MultipartFile mpf = multipartRequest.getFile(itr.next());
			 * String originFileName = mpf.getOrigin'alFilename(); System.out.println(
			 * "FILE_INFO: "+originFileName); //받은 파일 리스트 출력
			 */

			MultipartFile mpf = multipartRequest.getFile(itr.next());

			String originalFilename = mpf.getOriginalFilename(); // 파일명

			// 파일 확장자 추출
			String fileExt = FileUtils.getFileExt(originalFilename);

			UUID uuid = UUID.randomUUID();
			targetFilename = uuid.toString() + "." + fileExt.toLowerCase();

			String fileFullPath = filePath + "/" + targetFilename; // 파일 전체 경로

			try {
				// 파일 저장
				mpf.transferTo(new File(fileFullPath)); // 파일저장 실제로는 service에서 처리

				System.out.println("originalFilename => " + originalFilename);
				System.out.println("fileFullPath => " + fileFullPath);

			} catch (Exception e) {
				System.out.println("postTempFile_ERROR======>" + fileFullPath);
				e.printStackTrace();
			}
			
			filenames.add(targetFilename);

		}
		
		JSONObject jobj = new JSONObject();
		jobj.put("img_type", img_type);
		jobj.put("img_id", img_id);
		jobj.put("files", filenames);

		return jobj.toJSONString();
	}
저작자 표시
신고


 

티스토리 툴바