티스토리 뷰
[ 피곤해.. 공개하기 민망하지만... 나름 열코딩한 소스 ]
Flex Source
(upload 부분 소스)
(upload후 exception발생시 처리부분 구현 필요)
validator 부분 태그
<mx:StringValidator id="stringValidator" property="text" minLength="1" required="true" requiredFieldError="필수 기재 항목입니다."/>
//최종 validation 체크 및 업로드
private function setRegAppl(event:MouseEvent):void {
// 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];
}
<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
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 = "";
}
}
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);
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);
}
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();
}
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
링크
- gmlduqrhdwn
- judyOh blog
- naplez.net [ SCJP 1.4 ]
- DB
- web
- 한글 Mozilla 포럼 [실전웹표준가이드]
- (블로그)웹표준연구소 [마루아라소프트]
- 웹 프로그램 및 디자인관련 강좌 사이트
- (블로그)검색엔진 최적화 | 검색엔진 마케팅
- DB 툴 [DB에 대한 정보]
- PHP( 객체 지향 언어로써의 PHP )
- w3c표준규격 번역
- 서버 주무르기
- 검색엔진 마스터
- apache-kr.org
- 한국 썬 개발자 네트워크
- 검색엔진 최적화 블로그
- 피라시스닷컴(SVN관련)
- 웹기반 DNS 서비스 DNSEver.com
- JEUS / Tmax / WebtoB
- 웹기반 무료 DNS서버
- JAVA 강좌
- 少年易老學難成, 一寸光陰不可輕. 未覺池塘春草夢, 階前梧…
- MyJavaServer ( JSP 무료 호스팅 )
- I GOT IT (IT`S CRADLE & INCUBA…
- Todayis(HS)
- oracleclub.com
- Prototype (JavaScript Framewor…
- JSPWiki (openframework.or.kr)
- 제갈장비(JAVA_BLOG)
- jakartaproject
- Oracle_download
- jQuery plugin
- Test
- 안드로이드 앱 개발
- 행복한 개발자입니다.
- Flex & etc
- Flex & Design
- (iBatis)참고
- FLEX참고 사이트
- 대용량파일에 대한 watchservice 참고
- win7 update pack
TAG
- Ajax
- 오라클
- Eclipse
- 시퀀스생성
- 뚜비
- 정보보호전문자격
- 구글
- sw기술자 경력관리
- 머먹구사냐
- mybatipse #egovframework3.8
- derby
- mysql
- apache
- SEO
- 다운로드
- excel
- GD
- 자동증가
- Linux
- java
- vi
- ASP
- 롤링
- find
- php
- DOM
- CSS
- 비교문
- iBatis
- flex
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함