File Upload / Download FORM SUBMIT A Controller Service Dao AJAX

Slides:



Advertisements
Similar presentations
Lecture 15: I/O and Parsing
Advertisements

 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 24: Servlets Outline 24.1 Introduction 24.2 Servlet Overview and Architecture Interface.
1.  Understanding about How to Working with Server Side Scripting using PHP Framework (CodeIgniter) 2.
Examples of Using Servlets and JSP Representation and Management of Data on the Internet.
Java Servlets and Java Server Pages Carol Wolf Computer Science.
Li Tak Sing COMPS311F. Static attributes in Servlets Since Servlets are also Java classes, you can also use static attributes to store values that can.
Chapter 7 Java Server Pages. Objectives Explain how the separation of concerns principle applies to JSP Describe the operation and life-cycle of a JSP.
Stanisław Osiński, 2002JSP – A technology for serving dynamic web content Java Server Pages™ A technology for serving dynamic web content Stanisław Osiński,
Java Servlets. Servlets When we run small Java programs within a browser these are referred to as Applets... And when we run small Java programs within.
1 JSP with Custom Tags Blake Adams Introduction Advanced Java Server Pages – Custom Tags Keyterms: - Tag Library Descriptor(TLD) - Tag Libraries.
Mark Dixon 1 09 – Java Servlets. Mark Dixon 2 Session Aims & Objectives Aims –To cover a range of web-application design techniques Objectives, by end.
SE-2840 Dr. Mark L. Hornick 1 Java Server Pages. HTML/JSPs are intended to be used as the views in an MVC- based web application Model – represents an.
CSC 2720 Building Web Applications JavaServer Pages (JSP) The Basics.
Application Specific Module Tutorial Akos Balasko 02/07/
® IBM Software Group © 2007 IBM Corporation Servlet Filtering
IS-907 Java EE World Wide Web - Overview. World Wide Web - History Tim Berners-Lee, CERN, 1990 Enable researchers to share information: Remote Access.
 2002 Prentice Hall. All rights reserved. 9.8 Multi-Tier Applications: Using JDBC from a Servlet Three-tier distributed applications –User interface –Business.
SOEN 6011 Software Engineering Processes Section SS Fall 2007 Dr Greg Butler
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
Mark Dixon 1 11 – Java Servlets. Mark Dixon 2 Session Aims & Objectives Aims –To cover a range of web-application design techniques Objectives, by end.
©SoftMoore ConsultingSlide 1 Filters. Filters can be used in a web application to intercept, examine, and possibly transform requests or responses associated.
13 Copyright © 2004, Oracle. All rights reserved. Adding Validation and Error Handling.
Georgia Institute of Technology Making Text for the Web part 2 Barb Ericson Georgia Institute of Technology March 2006.
OOSD Using Java CBTS Framework. 11/2/04CBTS2 Servlet  A servlet is a Java program that can extends Web server’s functionality.  Servlets interact with.
#SummitNow Workflow Dashboard Custom Dashlet (Replacement for My Tasks) 14 November 2013 Bill Young, Flatirons Solutions.
ㅇ 데이터베이스 연동 지원 - 템플릿 클래스를 통한 데이터 접근 지원 - 의미있는 예외 클래스 제공 - 트랜잭션 처리 ㅇ Connection / PreparedStatement / ResultSet / try-catch 등 JDBC 중복 코드 제거 JDBC.
Presented by Alexey Vedishchev Developing Web-applications with Grails framework American University of Nigeria, 2016 Uploading and Downloading Files.
CS520 Web Programming Spring – Web MVC Chengyu Sun California State University, Los Angeles.
CS520 Web Programming Spring – Web MVC Chengyu Sun California State University, Los Angeles.
JSP java server pages.
Introduction to Servlets
CS3220 Web and Internet Programming Introduction to Java Servlets
Web Engineering Lecture-08.
Streams, File I/O and Scanner class
Spring Filters Spring Interceptors SoftUni Team Spring Interceptors
Registration, Login, Thymeleaf
Allowing File Uploads.
CS520 Web Programming Bits and Pieces of Web Programming (II)
Developing JavaServer Pages
JDBC & Servlet CSE 4504/6504 Lab.
>> PHP: File Uploads
CS520 Web Programming Spring – Inversion of Control
CS3220 Web and Internet Programming Generating HTTP Responses
J2EE Lecture 7: Spring – Spring MVC
Writing a Custom DispatchHandler
CSE 102 Introduction to Web Design and Programming
File Upload in ASP.NET Ivaylo Kenov Technical Assistant
I/O Basics.
Accessing Files in Java
V. Gyurjyan Clas12 Software Meeting
CS 190 Lecture Notes: Exception Handling
CS 190 Lecture Notes: Exception Handling
SERVLETS AND JDBC.
Java Server Pages.
Jagdish Gangolly State University of New York at Albany
Servlets and JSP 20-Nov-18 servletsJSP.ppt.
null, true, and false are also reserved.
Advanced Java programming in J2EE Chapter 1
CS5220 Advanced Topics in Web Programming Spring – Web MVC
© copyright Janson Industries 2011
with a value of javascript:onclick=resizeWindow()
Spring MVC Part 2 Spencer Uresk.
CS5220 Advanced Topics in Web Programming Spring – Web MVC
CS3220 Web and Internet Programming Introduction to Java Servlets
Sadalage & Fowler (Amazon)
Cookie and Session Bayu Priyambadha, S.Kom.
Introduction to Java Servlets
Exceptions and Exception Handling
Allowing File Uploads.
Presentation transcript:

File Upload / Download FORM SUBMIT A Controller Service Dao AJAX B Controller NAS DB

File Upload / Download ㅇ 필요 라이브러리 - commons-fileupload.jar - commons-io.jar - jquery.form.js ㅇ DB Table

File Upload / Download ㅇ 프로젝트 전체 구조 ㅇ Package 구조

dispatcher-servlet.xml (1 / 3) <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="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 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> <context:component-scan base-package="mvc.spring" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean>

dispatcher-servlet.xml (2 / 3) <!-- MessageConverter --> <bean class="org.springframework.web.servlet.mvc.annotation. AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter. StringHttpMessageConverter" /> <bean class="org.springframework.http.converter.json. MappingJacksonHttpMessageConverter" /> </list> </property> </bean> <!-- Multipart Resolver --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons. CommonsMultipartResolver"> <!-- maximum file size in bytes 50MB --> <property name="maxUploadSize" value="52428800" />

dispatcher-servlet.xml (3 / 3) <!-- Properties --> <util:properties id="config" location="/WEB-INF/config.properties" /> <!-- Data Source --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="#{config['db.driver']}" /> <property name="url" value="#{config['db.url']}" /> <property name="username" value="#{config['db.id']}" /> <property name="password" value="#{config['db.pw']}" /> </bean> <!-- Jdbc Template --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <constructor-arg ref="dataSource" /> </beans>

config.properties /WEB-INF db.driver=oracle.jdbc.driver.OracleDriver db.url=jdbc:oracle:thin:@localhost:1521:xe db.id=scott db.pw=tiger

FileController(1 / 3) Package : mvc/spring/controller @Controller public class FileController { @Autowired FileService fileService; /* submit file upload form */ @RequestMapping(value="fileUpload.do", method=RequestMethod.GET) public ModelAndView fileUploadForm() { ModelAndView mav = new ModelAndView(); mav.setViewName("file/fileUpload_submit"); return mav; } /* submit file upload */ @RequestMapping(value="fileUpload.do", method=RequestMethod.POST) public ModelAndView fileUpload(MultipartRequest mRequest) { boolean result = fileService.uploadFile(mRequest); mav.addObject("result", result); mav.setViewName("file/fileUpload_result");

FileController(2 / 3) Package : mvc/spring/controller /* ajax file upload form */ @RequestMapping(value="fileUploadAjax.do", method=RequestMethod.GET) public ModelAndView fileUploadAjaxForm() { ModelAndView mav = new ModelAndView(); View view = new InternalResourceView( “/WEB-INF/views/file/fileUpload_ajax.jsp"); mav.setView(view); return mav; } /* ajax file upload */ @RequestMapping(value="fileUploadAjax.do", method=RequestMethod.POST) @ResponseBody public Map<String, Object> fileUploadAjax(MultipartRequest mRequest) { boolean result = fileService.uploadFile(mRequest); Map<String, Object> map = new HashMap<String, Object>(); map.put("result", result); return map;

FileController(3 / 3) Package : mvc/spring/controller /* file download */ @RequestMapping("fileDownload.do") public ModelAndView fileDownload(@RequestParam("seqNo") String seqNo, @RequestParam("num") String num) { ModelAndView mav = new ModelAndView(); Map<String, Object> map = new HashMap<String, Object>(); map.put("seqNo", seqNo); map.put("num", num); List<Map<String, Object>> list = fileService.getFileList(map); Map<String, Object> data = new HashMap<String, Object>(); String fileName = (String) list.get(0).get("DSP_FILE_NAME"); String filePath = list.get(0).get("FILE_PATH") + File.separator + list.get(0).get("FILE_NAME"); File file = new File(filePath); data.put("file", file); data.put("fileName", fileName); mav.addObject("data", data); mav.setView(new FileDownloadView()); return mav; }

FileService Package : mvc/spring/service public interface FileService { public boolean uploadFile(MultipartRequest mRequest); public List<Map<String, Object>> getFileList(Map<String, Object> map); }

FileServiceImpl (1 / 4) Package : mvc/spring/service @Service public class FileServiceImpl implements FileService { @Autowired FileAtchDao fileAtchDao; @Override public boolean uploadFile(MultipartRequest mRequest) { boolean isSuccess = false; String uploadPath = "/spring/upload"; File dir = new File(uploadPath); if(!dir.isDirectory()) { dir.mkdirs(); }

FileServiceImpl (2 / 4) Package : mvc/spring/service Iterator<String> iter = mRequest.getFileNames(); while(iter.hasNext()) { // HTML input tag name String htmlName = iter.next(); // Multipart File MultipartFile mFile = mRequest.getFile(htmlName); // Original File name String oFileName = mFile.getOriginalFilename(); // Save File name String saveFileName = oFileName; // Save File size long fileSize = mFile.getSize(); String realFilePath = uploadPath + File.separator + saveFileName; if(!saveFileName.equals("") && new File(realFilePath).exists()) { saveFileName = saveFileName + "_" + System.currentTimeMillis(); realFilePath = uploadPath + File.separator + saveFileName; }

FileServiceImpl (3 / 4) Package : mvc/spring/service try { Map<String, Object> map = new HashMap<String, Object>(); map.put("seqNo", 1); map.put("filePath", uploadPath); map.put("fileName", saveFileName); map.put("dspFileName", oFileName); map.put("fileSize", fileSize); fileAtchDao.insertFileAtch(map); mFile.transferTo(new File(realFilePath)); isSuccess = true; } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { } return isSuccess;

FileServiceImpl (4 / 4) Package : mvc/spring/service @Override public List<Map<String, Object>> getFileList(Map<String, Object> map) { List<Map<String, Object>> list = fileAtchDao.selectFileAtch(map); return list; }

FileAtchDao Package : mvc/spring/dao public interface FileAtchDao { public boolean insertFileAtch(Map<String, Object> map); public List<Map<String, Object>> selectFileAtch(Map<String, Object> map); }

FileAtchDaoImpl (1 / 2) Package : mvc/spring/dao @Repository public class FileAtchDaoImpl implements FileAtchDao { @Autowired JdbcTemplate template; @Override public boolean insertFileAtch(Map<String, Object> map) { StringBuffer sql = new StringBuffer(); sql.append("INSERT INTO FILE_ATCH"); sql.append(" (NUM, SEQ_NO, FILE_PATH, FILE_NAME, DSP_FILE_NAME, FILE_SIZE)"); sql.append(" VALUES "); sql.append(" ((SELECT NVL(MAX(TO_NUMBER(NUM)), 0) + 1 FROM FILE_ATCH), ?, ?, ?, ?, ?) "); int result = template.update(sql.toString(), map.get("seqNo"), map.get("filePath"), map.get("fileName"), map.get("dspFileName"), map.get("fileSize")); return result > 0 ? true : false; }

FileAtchDaoImpl (2 / 2) Package : mvc/spring/dao @Override public List<Map<String, Object>> selectFileAtch(Map<String, Object> map) { StringBuffer sql = new StringBuffer(); sql.append("SELECT NUM, SEQ_NO, FILE_PATH"); sql.append(" , FILE_NAME, DSP_FILE_NAME, FILE_SIZE"); sql.append(" FROM FILE_ATCH"); sql.append(" WHERE NUM = ? AND SEQ_NO = ?"); List<Map<String, Object>> list = template.queryForList(sql.toString(), map.get("num"), map.get("seqNo")); return list; }

fileUpload_submit.jsp /WEB-INF/views/file <%@ 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>파일 업로드 화면</title> </head> <body> <form action="./fileUpload.do" method="post" enctype="multipart/form-data"> 파일첨부 1 : <input type="file" name="file1" /> <br /> 파일첨부 2 : <input type="file" name="file2" /> 파일첨부 3 : <input type="file" name="file3" /> <input type="submit" value="upload" /> </form> </body> </html>

fileUpload_ajax.jsp (1 / 2) /WEB-INF/views/file <%@ 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>파일 업로드 화면</title> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script src="./js/jquery.form.js"></script> <script> $(document).ready(function() { $("input[type=submit]").bind("click", function() { $("form").ajaxSubmit({ success : function(data) { alert(data.result); }, error : function(error) { alert("요청 처리 중 오류가 발생하였습니다."); } }); return false; </script> </head>

fileUpload_ajax.jsp (2 / 2) /WEB-INF/views/file <body> <form action="./fileUploadAjax.do" method="post" enctype="multipart/form-data"> 파일첨부 1 : <input type="file" name="file1" /> <br /> 파일첨부 2 : <input type="file" name="file2" /> 파일첨부 3 : <input type="file" name="file3" /> <input type="submit" value="upload" /> </form> </body> </html>

fileUpload_result.jsp /WEB-INF/views/file <%@ 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>파일 업로드 결과</title> </head> <body> <h1>${result}</h1> </body> </html>

FileDownloadView Package : mvc/spring/view public class FileDownloadView extends AbstractView { @Override protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> data = (Map<String, Object>) model.get("data"); File file = (File) data.get("file"); String oFileName = (String) data.get("fileName"); response.setContentType(this.getContentType()); response.setContentLength((int)file.length()); response.setHeader("Content-Disposition", "attachment; filename=\"" + java.net.URLEncoder.encode(oFileName, "UTF-8") + "\";charset=\"UTF-8\""); response.setHeader("Content-Transfer-Encoding", "binary"); response.setHeader("Pragma", "no-cache"); OutputStream out = response.getOutputStream(); FileInputStream in = null; in = new FileInputStream(file); FileCopyUtils.copy(in, out); out.close(); out.flush(); }