300x250
반응형
웹에서 Drag&Drop로 fileupload를 하는 예제를 작성해 보겠습니다.
일단 file을 java로 받기위해 pom.xml 에 Commons FileUpload를 적어줍니다.
아래 설정을 보시고 36~47 라인을 추가해 주세요.
(입력하는 부분만 적으면 어디에 어떻게 입력하는지 어려우실까봐 제 pom.xml 설정을 모두 적었습니다. 해당 라인만 추가해주시면 됩니다.)
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.neowiz</groupId>
<artifactId>myapp</artifactId>
<name>SpringTest</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<java-version>1.6</java-version>
<org.springframework-version>3.1.1.RELEASE</org.springframework-version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<org.slf4j-version>1.6.6</org.slf4j-version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- Commons FileUpload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
<scope>runtime</scope>
</dependency>
<!-- @Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<additionalProjectnatures>
<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
</additionalProjectnatures>
<additionalBuildcommands>
<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
</additionalBuildcommands>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<mainClass>org.test.int1.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
파일을 읽을수 있도록 multipartResolver를 추가해 줍니다.
아래 설정을 참고 하시어 24~30 라인을 추가 시켜 주세요.
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<beans:bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- max upload size in bytes -->
<beans:property name="maxUploadSize" value="20971520" /> <!-- 20MB -->
<!-- max size of file in memory (in bytes) -->
<beans:property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->
</beans:bean>
<context:component-scan base-package="com.husk.myapp" />
</beans:beans>
Drag&Drop 받을 화면을 작성해 보겠습니다.
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();
});
//drag 영역 클릭시 파일 선택창
objDragAndDrop.on('click',function (e){
$('input[type=file]').trigger('click');
});
$('input[type=file]').on('change', function(e) {
var files = e.originalEvent.target.files;
handleFileUpload(files,objDragAndDrop);
});
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 = "/fileUpload/post"; //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 or Browse Files</div>
<input type="file" name="fileUpload" id="fileUpload" style="display:none;" multiple/>
</body>
</html>
Controller에서 파일을 받는 부분을 작성하겠습니다.
HomeController.java
package com.husk.myapp;
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 HomeController {
@RequestMapping(value = "/fileUpload", method = RequestMethod.GET)
public String dragAndDrop(Model model) {
return "fileUpload";
}
@RequestMapping(value = "/fileUpload/post") //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";
}
}
Controller 에서 받은 파일을 Service로 넘겨 저장하는 작업을 진행하시면 됩니다.
출처 : https://huskdoll.tistory.com/294
원글 참고: http://hayageek.com/drag-and-drop-file-upload-jquery/
300x250
반응형
'Back-End > Spring' 카테고리의 다른 글
[JPA] save , saveAll 비교 (0) | 2023.02.10 |
---|---|
[JPA] 연관관계 매핑하는 방법 (0) | 2023.02.10 |
[Spring Security] 로그인시 발생되는 오류 문구를 내가 설정해보자 (0) | 2023.02.10 |
[Spring Boot] 로그인 및 사용자 인증 정보 참조 (0) | 2023.02.10 |
[Spring Boot] Spring boot + hibernate로 프로젝트 생성하기 (0) | 2023.02.10 |