네이버의 "샤크의 자바프로그램"이라는 카페에서 무단복사한 글입니다. -_-;

Flex 와 Java를 이용한 파일 업로드 원문


Flex 와 Java를 이용한 파일 업로드 예제 입니다.
    아래 예제는 Tomcat-5.5.23 버전에서 테스트를 한 코드입니다.

1.     서버 파일 업로드 클래스 구현 – UploadServlet.java
업로드는 apache fileupload 라이브러리를 사용하여 구현됩니다.

import java.io.File;

import java.io.IOException;

import java.util.List;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

 

public class UploadServlet extends HttpServlet {

 

           public void doPost(HttpServletRequest request, HttpServletResponse response)

                                throws ServletException, IOException {

                     try {

                                System.out.println("Start Upload!");

                                request.setCharacterEncoding("UTF-8");

                                // Create a factory for disk-based file items

                                DiskFileItemFactory factory = new DiskFileItemFactory();

 

                                // Set factory constraints

                                factory.setSizeThreshold(1024 * 1024 * 2);

                                factory.setRepository(new File(getServletContext().getRealPath("/WEB-INF/uploadData")));

 

                                // Create a new file upload handler

                                ServletFileUpload upload = new ServletFileUpload(factory);

                                // Set overall request size constraint

                                upload.setSizeMax(-1);

 

                                List list = upload.parseRequest(request);

                                for (int i=0,ii=list.size();i<ii;i++) {

                                          FileItem fileItem = (FileItem)list.get(i);

                                          //첨부파일 체크

                                          if("FileData".equals(fileItem.getFieldName()))

                                          {

                                                     File file = new File(getServletContext().getRealPath(

                                                                          "/upload/" + fileItem.getName()));

 

                                                     File upDir = file.getParentFile();

                                                     if(!upDir.isFile()&&!upDir.isDirectory()){

                                                                upDir.mkdirs();

                                                     }

                                                    

                                                     fileItem.write(file);

                                          }

                                }

                     } catch (Exception e) {

                                e.printStackTrace();

                                throw new ServletException(e);

                     }

           }

 

           public void doGet(HttpServletRequest request, HttpServletResponse response)

                                throws IOException {

                     response.getWriter().write("UploadServlet run on http ...");

           }

}

 

2.     Flex 파일 업로드 UI 구현 – FlexUpload.mxml
업로드 파일의 필드 이름은 “FileData”이름으로 전송됩니다. 당근 서버의 업로드 클래스는

“FileData”
이름으로 파라미터를 처리하겠죠..

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">

           <mx:Script>

                     <![CDATA[

                                import mx.controls.Alert;

                               import mx.events.CloseEvent;

                              

                               private var file:FileReference;

 

                                private function fileOpen():void

                                {

                                          file = new FileReference();

                                          //파일 선택 이벤트 처리

                                          file.addEventListener("select", fileSelected);

                                          file.browse();

                                         

                                }

                                private function fileSelected(e:Event):void

            {

                Alert.show("Upload " + file.name + " ("+Math.round(file.size/1024)+"KB)?",

                           "Upload Confirmation",

                           Alert.YES|Alert.NO,

                           null,

                           proceedWithUpload);

            }

           

            private function proceedWithUpload(e:CloseEvent):void

            {

                if (e.detail == Alert.YES)

                {

                    //선택한 파일 업로드 시작

                    var urlRequest:URLRequest = new URLRequest("http://localhost:8080/upload");

                    file.upload(urlRequest,"FileData",false);

                }

            }

 

                     ]]>

           </mx:Script>

           <mx:Button label="파일추가" click="fileOpen()">

                    

           </mx:Button>

</mx:Application>

 

3.     UploadServlet 설정

A.     ~/WEB-INF/lib/폴더에 2개의 jar파일을 복사합니다.
(commons-fileupload-1.1.jar, commons-io-1.2.jar)

B.      ~/WEB-INF/web.xml 파일을 수정합니다. 빨간색 글씨로 된 부분을 추가합니다.

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"

    version="2.4">

 

  <display-name>Welcome to Tomcat</display-name>

  <description>

     Welcome to Tomcat

  </description>

 

<!-- JSPC servlet mappings start -->

 

    <servlet>

        <servlet-name>org.apache.jsp.index_jsp</servlet-name>

        <servlet-class>org.apache.jsp.index_jsp</servlet-class>

    </servlet>

 

    <servlet-mapping>

        <servlet-name>org.apache.jsp.index_jsp</servlet-name>

        <url-pattern>/index.jsp</url-pattern>

    </servlet-mapping>

<servlet>

        <servlet-name>uploadServlet</servlet-name>

        <servlet-class>UploadServlet</servlet-class>

        <load-on-startup>1</load-on-startup>

    </servlet>

    <servlet-mapping>

        <servlet-name>uploadServlet</servlet-name>

        <url-pattern>/upload</url-pattern>

    </servlet-mapping>

<!-- JSPC servlet mappings end -->

 

</web-app>

 

C.      UploadServlet.class 파일을 ~/WEB-INF/classes 폴더에 복사합니다.

4.     서버를 실행한 후 http://localhost:8080/upload 호출하여 등록한 업로드 서블릿이 작동하는지 테스트 합니다. 정상적으로 등록이 되었다면 “UploadServlet run on http …”라는 메시지가 화면에 표시가 됩니다.

5.     이제 FileUpload.swf파일을 실행한 후 파일을 선택한 다음 업로드를 합니다.
업로드가 성공하였다면 웹루트에 upload폴더가 생성이 되고 폴더 안에 선택한 파일이 생성 됩니다.

+ Recent posts