Android

[Android] jsp 페이지를 통해 서버에 있는 파일 다운로드

박진만 2013. 9. 27. 18:23
반응형

서버쪽 jsp 소스

<%@ page language="java" contentType="text/html; charset=euc-kr" pageEncoding="euc-kr"%> 
<%@ page import="java.io.*,java.net.URLEncoder"%> 
<%       
	String filename = "파일명";     
	String filename2 = new String(filename.getBytes("euc-kr"),"8859_1");     
    response.setContentType("application/octet-stream");     
    File file = new File ("D:/JEUS60/webhome/app_home/MobileService/WebContent/file/cmp/"+filename);     
    byte[] bytestream = new byte[(int)file.length()];      
    response.setHeader("Content-Disposition", "attachment;filename="+ filename2 + ";");     
    response.setHeader("Content-Transfer-Encoding", "binary;");     
    response.setContentLength((int)file.length());     
    FileInputStream filestream = new FileInputStream(file);     
    int i = 0, j = 0;     
    
    while((i = filestream.read()) != -1) {     
    	bytestream[j] = (byte)i;     
        j++;     
    }          
    
    OutputStream outStream = response.getOutputStream();     
    outStream.write(bytestream);     
    outStream.close(); 
    %> 
    <meta http-equiv="Content-Type" content="text/html; charset=euc-kr"> 
    <title>타이틀</title>

안드로이드쪽 java 소스

	String File_Name;
    String File_extend;
    String fileURL; // URL 
    String Save_Path; 
    String Save_folder;   
    ProgressDialog progress; 
    DownloadThread dThread; 
    
    @Override  
    public void onCreate(Bundle savedInstanceState) {
    	
    	super.onCreate(savedInstanceState);      
        setContentView(R.layout.siteinfo_detail);   
        File_Name = "test.pdf";   
        File_extend = "pdf";      
        fileURL = "http://www.naver.com/FileDownload.jsp"; // URL     
        Save_folder = "/mydown";      
        
        // 다운로드 경로를 외장메모리 사용자 지정 폴더로 함.   
        String ext = Environment.getExternalStorageState();      
        
        if(ext.equals(Environment.MEDIA_MOUNTED)) {    
        	Save_Path = Environment.getExternalStorageDirectory().getAbsolutePath() + Save_folder;   
        }  
        
        //파일 다운로드 버튼 클릭  
        btn_pdfDownload = (Button)findViewById(R.id.btn_pdfDownload);  
        btn_pdfDownload.setOnClickListener(new OnClickListener() {    
        	@Override    
            public void onClick(View v) {          
            	File dir = new File(Save_Path);
                
                // 폴더가 존재하지 않을 경우 폴더를 만듬     
                if (!dir.exists()) {      
                	dir.mkdir();     
                }
                
                // 다운로드 폴더에 동일한 파일명이 존재하는지 확인해서 없으면 다운받고 있으면 해당 파일 실행시킴.     
                if (new File(Save_Path + "/" + File_Name).exists() == false) {      
                	progress = ProgressDialog.show(Siteinfo_detail.this, "","파일 다운로드중..");      
                    dThread = new DownloadThread(fileURL, Save_Path + "/" + File_Name);      
                    dThread.start();     
                } else {      
                	showDownloadFile();     
                }           
            }   
        });  
    }    
    
    // 다운로드 쓰레드로 돌림..     
    class DownloadThread extends Thread {
    	
    	String ServerUrl;
        String LocalPath;
        
        DownloadThread(String serverPath, String localPath) {
        	ServerUrl = serverPath;    
            LocalPath = localPath;   
        }      
        
        @Override   
        public void run() {
        	URL imgurl;
            int Read;
            
            try {
            	imgurl = new URL(ServerUrl);     
                HttpURLConnection conn = (HttpURLConnection) imgurl.openConnection();     
                conn.connect();     
                int len = conn.getContentLength();          
                byte[] tmpByte = new byte[len];          
                InputStream is = conn.getInputStream();     
                File file = new File(LocalPath);     
                FileOutputStream fos = new FileOutputStream(file);          
                
                for (;;) {      
                	Read = is.read(tmpByte);            
                    
                    if (Read <= 0) {       
                    	break;      
                    }
                    
                    fos.write(tmpByte, 0, Read);     
                }          
                
                is.close();     
                fos.close();     
                conn.disconnect();         
            } catch (MalformedURLException e) {     
            	Log.e("ERROR1", e.getMessage());    
            } catch (IOException e) {     
            	Log.e("ERROR2", e.getMessage());     
                e.printStackTrace();    
            }    
            
            mAfterDown.sendEmptyMessage(0);   
        }  
    }    
    
    Handler mAfterDown = new Handler() {   
    	@Override   
        public void handleMessage(Message msg) {        
        	progress.dismiss();        
            // 파일 다운로드 종료 후 다운받은 파일을 실행시킨다.    
            showDownloadFile();   
        }  
    };    
    
    private void showDownloadFile() {      
    	Intent intent = new Intent();   
        intent.setAction(android.content.Intent.ACTION_VIEW);      
        File file = new File(Save_Path + "/" + File_Name);      
        
        //파일 확장자 별로 mime type 지정해 준다.   
        if (File_extend.equals("pdf")) {    
        	intent.setDataAndType(Uri.fromFile(file), "application/pdf");   
        }      
        
        try{        
        	startActivity(intent);       
        } catch(ActivityNotFoundException e){    
        	Toast.makeText(Siteinfo_detail.this, "해당파일을 실항할 수 있는 어플리케이션이 없습니다.\n파일을 열 수 없습니다.", Toast.LENGTH_SHORT).show();    
            e.printStackTrace();   
        }  
    } 
} 
반응형