티스토리 뷰

web 2.0/FLEX

[Flex] FileUpload & DownLoad

미련곰 2009. 9. 15. 21:27

[ 피곤해.. 공개하기 민망하지만... 나름 열코딩한 소스 ]

Flex Source
(upload 부분 소스)
(upload후 exception발생시 처리부분 구현 필요)

validator 부분 태그
<mx:StringValidator id="stringValidator" property="text" minLength="1" required="true" requiredFieldError="필수 기재 항목입니다."/>

//최종 validation 체크 및 업로드
private function setRegAppl(event:MouseEvent):void {
    //validation text 체크할 ID
    var listeners:Array = [tx_addr2, tx_telnoOfnum, tx_telnoNo, tx_iContent];
    var isValid:Boolean = true;
    for each(var listener:Object in listeners) {
        stringValidator.source = listener;
        vResult = stringValidator.validate();
        if(vResult.type == ValidationResultEvent.INVALID) {
            isValid = false;
        }
    }
    if(isValid) {
        //File Upload
        if(fr && StringUtil.trim(tx_fileNm.text) != "") {
            var today:Date = new Date();
            var fileName:Array = fr.name.split("."); 
            //물리 file명
            filePhysiclNm = String(Date.parse(today)) + "_" + String(Math.floor(Math.random()*10)) + '.' + fileName[1];
            var variables:URLVariables = new URLVariables();
            variables.fileMaxSize = FileCont.FILE_MAX_SIZE;
            variables.filePhysiclNm = filePhysiclNm;
            variables.uploadPath = FileCont.FILE_UPLOAD_PATH; 
    
            var urlRequest:URLRequest = new URLRequest(UrlUtil.getUrlRoot("uploadUnity.do"));
            urlRequest.method = URLRequestMethod.POST; 
            urlRequest.data = variables;
            fr.upload(urlRequest);    
        } else {
            uploadComplete();
        }
    } else {
        regFaildTxt.text = "*.필수 항목을 기재하지 않으셨습니다.";
        var timer:Timer = new Timer(3000, 1);
        timer.addEventListener("timer", returnErrorMsg);
        timer.start();
        return;
    }   
    function returnErrorMsg():void {
        regFaildTxt.text = "";
    }
}
 
//  listener
private function configureListeners(dispatcher:IEventDispatcher):void {
    dispatcher.addEventListener(Event.SELECT, fileSelect);
    dispatcher.addEventListener(Event.COMPLETE, uploadComplete);
    dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, error);
    dispatcher.addEventListener(IOErrorEvent.IO_ERROR, error);
    function error(event:*):void {
        Alert.show(event.toString(), "Error");
    }
}
         
//upload file 선택
private function fileSelect(e:Event):void {
    if(fr.size < FileCont.FILE_MAX_SIZE) {
        tx_fileNm.text = fr.name;
        fileSizeField.text = "[ " + (Math.round(fr.size / 1024)).toString() + "KB ]";
    } else {
        Alert.show("파일크기: "+(Math.round(fr.size / 1024)).toString()+"KB\n
                            파일크키는 2048KB(2MB)를 넘을 수 없습니다.", "경고");
    }
}

//파일첨부 Btn click(최초 업로드 버튼 클릭)
private function openFileBrowse(e:MouseEvent):void {
    if(!fr) {
        fr = new FileReference();
    }
    configureListeners(fr);
    fr.browse(FileCont.fileFilterArr());
}


//FileCont.fileFilterArr() 부분
public static function fileFilterArr():Array {
    var allFilter:FileFilter = new FileFilter("업로드가능파일",                                "*.jpg;*.gif;*.png;*.pdf;*.doc;*.txt;*.hwp;*.xls;*.xlsx;*.ppt;*.pptx");
    var imagesFilter:FileFilter = new FileFilter("이미지파일(*.jpg; *.gif; *.png)", "*.jpg;*.gif;*.png");
    var docFilter:FileFilter = new FileFilter("문서파일(*.pdf; *.doc; *.txt; *.hwp; *.xls; *.xlsx; *.ppt; *.pptx)",   "*.pdf;*.doc;*.txt;*.hwp;*.xls;*.xlsx;*.ppt;*.pptx");
    return [allFilter, imagesFilter, docFilter];
}


(download 부분 소스)
private function download():void {
    if (tx_fileLogicNm.text == "등록된 파일이 없습니다."){
        tx_fileLogicNm.buttonMode = false;
    }else{
        tx_fileLogicNm.buttonMode = true;
        if(!fileRef) {
            fileRef = new FileReference();
        }
        configureListeners(fileRef);

        var filePhysiclNm:String = contentData.filePhysiclNm;
        var fileLogicNm:String = contentData.fileLogicNm;
        var variables:URLVariables = new URLVariables();
        var urlRequest:URLRequest = new URLRequest(UrlUtil.getUrlRoot("JAVA SERVLET URL"));
        variables.filePhysiclNm = filePhysiclNm;
        variables.uploadPath    = FileCont.FILE_UPLOAD_PATH;
        urlRequest.method = URLRequestMethod.POST;
        urlRequest.data = variables;
        fileRef.download(urlRequest, fileLogicNm);      
    } 
}

private function configureListeners(dispatcher:IEventDispatcher):void {
    //dispatcher.addEventListener(Event.COMPLETE, completeHandler);
    dispatcher.addEventListener(Event.OPEN, openHandler);
    dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
    dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
    dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
    dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
}

private function httpStatusHandler(event:HTTPStatusEvent):void {
    trace("httpStatusHandler: " + event);
}

private function cancelHandler(event:Event):void {
    trace("cancelHandler: " + event);
}

private function ioErrorHandler(event:IOErrorEvent):void {
    Alert.show("파일이 존재하지 않습니다.\n Error [:" + event.text + "]", "Error");
}

private function openHandler(event:Event):void {
    trace("openHandler: " + event);
}

private function progressHandler(event:ProgressEvent):void {
    var file:FileReference = FileReference(event.target);
    trace("progressHandler name=" + file.name + " bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal);
}

private function securityErrorHandler(event:SecurityErrorEvent):void {
    trace("securityErrorHandler: " + event);
}

private function selectHandler(event:Event):void {
    var file:FileReference = FileReference(event.target);
    trace("selectHandler: name=" + file.name + " URL=" + downloadURL.url);
}


Java Source
(commons-fileupload 사용)
(exception 처리 필요)
- upload -

        try {
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
           
            if (isMultipart) {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setHeaderEncoding("UTF-8");
                request.setCharacterEncoding("UTF-8");
               
                List items = upload.parseRequest(request);
                Iterator iter = items.iterator();
               
                long fileMaxSize    = 0;       //file upload 용량 제한
                String filePhysiclNm = "";    //물리파일명
                String uploadPath   = "";      //파일저장경로
               
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                   
                    if (item.isFormField()) {
                        if(item.getFieldName().equals("fileMaxSize")){
                            fileMaxSize = Long.parseLong(item.getString());
                        } else if(item.getFieldName().equals("filePhysiclNm")) {
                            filePhysiclNm = item.getString("UTF-8");
                        } else if(item.getFieldName().equals("uploadPath")) {
                            uploadPath = item.getString("UTF-8");
                        }
                    } else {
                        if (item.getSize() < fileMaxSize) {
                            String filePath = CommonUtil.getRealPath(uploadPath + filePhysiclNm);
                            //System.out.println("filePath:::::::::"+filePath);
                            File uploadedFile = new File(filePath);
                           
                            File upDir = uploadedFile.getParentFile();
                            if(!upDir.isDirectory()){
                                upDir.mkdirs();
                            }
                            if (!uploadedFile.exists()) {
                                uploadedFile.createNewFile();
                            }
                            item.write(uploadedFile);
                        } else {
                        }
                    }
                }
            } else {
            }     
        } catch (Exception ex) {
        }

   
- download -

        String filePhysiclNm = request.getParameter("filePhysiclNm");
        String downloadPath = request.getParameter("uploadPath");        
        try {
            String filePath = CommonUtil.getRealPath(downloadPath + filePhysiclNm);
            System.out.println("filePath:::::::::"+filePath);
            File downloadFile = new File(filePath);
           
            int length = 0;
            ServletOutputStream op = response.getOutputStream();
            ServletContext context = getServlet().getServletConfig().getServletContext();
            String mimetype = context.getMimeType(filePhysiclNm);
           
            response.setContentType((mimetype != null)?mimetype:"application/octet-stream");
            response.setContentLength((int)downloadFile.length());
            response.setHeader("Content-Disposition", "attachment;filename=\"" + filePhysiclNm + "\"" );
           
            byte[] bbuf = new byte[2048];
            DataInputStream in = new DataInputStream(new FileInputStream(downloadFile));
            while ((in != null) && ((length = in.read(bbuf)) != -1)) {
                op.write(bbuf, 0, length);
            }
            in.close();
            op.flush();
            op.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함