'Programming/JAVA'에 해당되는 글 1

  1. 2010.03.11 아주 심플한 업로드
Programming/JAVA | Posted by locke 2010.03.11 13:24

아주 심플한 업로드

정식으로 만들기도 귀찮고해서(망할 프레임워크..ㅠㅠ) 아주 간단하게 만든 파일 업로드 소스. 첨부한 cos.jar를 lib에 추가하고 쓸것.

<%@ page contentType="text/html; charset=utf-8" %>
<%@ page import="java.io.*" %>
<%@ page import="com.oreilly.servlet.MultipartRequest" %>
<%@ page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@ include file="config.jsp" %>
<%

int maxSize  = 1024*1024*30;
 
String root=request.getSession().getServletContext().getRealPath("/");
String uploadFile="";


try{
   MultipartRequest multi= new MultipartRequest(request,SAVE_DIR,maxSize, new DefaultFileRenamePolicy());
   
   uploadFile=multi.getFilesystemName("file");
  
  
   File oldFile = new File(SAVE_DIR+uploadFile);

  
   uploadFile= new String(uploadFile.getBytes("8859_1"),"utf-8");

    String fileName = "";
    for (int i=1; i < 21; i++) {
        int rnd = 1 + (int)(Math.random() * 52);
        rnd = (rnd > 26) ? rnd + 70 : rnd + 64;
        fileName = fileName + (char)(rnd);
    }

   File newFile = new File(SAVE_DIR+fileName+".jpg");

   long dataLength;
   dataLength = oldFile.length();

   if(!oldFile.renameTo(newFile)){
        byte[] buf = new byte[1024];
        FileInputStream fin = new FileInputStream(oldFile);
        FileOutputStream fout = new FileOutputStream(newFile);
        int read = 0;
        while((read=fin.read(buf,0,buf.length))!=-1){
         fout.write(buf, 0, read);
        }
        fin.close();
        fout.close();
        oldFile.delete();
    }   

String saveAsFile = SAVE_DIR + fileName;

//System.out.println("{ fileUrl:'" + SAVE_URL + fileName+".jpg" + "', filePath:'" + saveAsFile+".jpg" +
// "', origName:'" + fileName+".jpg" + "', fileName:'" + fileName+".jpg" + "', fileSize:'"+dataLength+"'}");

 out.println("{ fileUrl:'" + SAVE_URL + fileName+".jpg" + "', filePath:'" + saveAsFile+".jpg" +
 "', origName:'" + fileName+".jpg" + "', fileName:'" + fileName+".jpg" + "', fileSize:'"+dataLength+"'}");

}catch(Exception e){e.printStackTrace();}

%>