2012-03-27 3 views
1

다운로드하려면 php 페이지를 사용하여 웹 서버에서 zip 파일을 다운로드하려고합니다. 내가 zip 파일에 정적 링크를 사용하여 다운로드하는 경우Android 다운로드 Zip (서버에서 이름을 바꿀 수 있음)

, 그것은 잘 작동하지만, 나는이 코드를 PHP 파일을 사용하여 다운로드하기 위해 노력하고있어 :

function file_list($d,$x){ 
    foreach(array_diff(scandir($d,1),array('.','..')) as $f)if(is_file($d.'/'.$f)&&(($x)?ereg($x.'$',$f):1))$l[]=$f; 
    return $l; 
} 

$arr = file_list("../download/",".zip"); 

$filename = $arr[0]; 
$filepath = "../download/".$arr[0]; 

if(!file_exists($filepath)){ 
    die('Error: File not found.'); 
} else { 
    // Set headers 
    header("Cache-Control: public"); 
    header("Content-Description: File Transfer"); 
    header("Content-Disposition: attachment; filename=$filename"); 
    header("Content-Type: application/zip"); 
    header("Content-Transfer-Encoding: binary"); 

    readfile($filepath); 
} 

난에서 PHP 파일을 액세스하는 경우 내 브라우저를 사용하면 zip을 다운로드 할 수 있습니다. 이 가정하지만 우편의 이름 getZip.php (PHP 파일 이름)이며, 파일 크기는 것처럼

이제 안드로이드 측면에서, 그것은이 다운로드를 수행하는 코드가 22

다운로드 Android의 자료

 int count; 

     try { 
      downloadCoords(); 
      URL url = new URL(aurl[0]); 
      URLConnection conexion = url.openConnection(); 
      conexion.connect(); 

      int lengthOfFile = conexion.getContentLength(); 
      Log.d("ANDRO_ASYNC", "Length of file: " + lengthOfFile); 

      File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()); 
      if(!f.isDirectory()){ 
       f.mkdirs(); 
      } 

      Uri u = Uri.parse(url.toString()); 
      File uf = new File(""+u); 
      zipname = uf.getName(); 
      Log.d("ANDRO_ASYNC", "Zipname: " + zipname); 

      File zipSDCARD = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+zipname); 
      if(!zipSDCARD.isFile()){ 
       Log.d("zipSDCARD.isFile()","false"); 

       InputStream input = new BufferedInputStream(url.openStream()); 
       OutputStream output = new FileOutputStream("/sdcard/" + zipname); 

       byte data[] = new byte[1024]; 

       long total = 0; 

       while ((count = input.read(data)) != -1) { 
        total += count; 
        publishProgress(""+(int)((total*100)/lengthOfFile)); 
        output.write(data, 0, count); 
       } 

       output.flush(); 
       output.close(); 
       input.close(); 
      } 
      successDownload = true; 
     } catch (Exception e) { 
      successDownload = false; 
      Log.e("Error","DownloadZip",e); 
     } 

수행해야 할 작업은 zipname과 ziplength도 올바르게 지정하는 것입니다.

미리 감사드립니다.

+0

안녕하십니까, 상황에 따라 [DownloadManager] (http://developer.android.com/reference/android/app/DownloadManager.html)를 사용할 수 있습니다. 이것은 당신을 위해 다운로드 (재시도 등)의 모든 핵심 기사를 처리합니다. – Renard

+0

@ Renard 도움이 될지 모르겠다. 정확히 똑같은 것을 성취 할 것이라고 생각한다. – silentw

답변

0

글쎄, 나는이 스크립트를 사용하여 화면에 동적으로 우편에 대한 링크를 작성하는 PHP를 사용하여 그것을 해결 :

: 안드로이드에 그런

function file_list($d,$x){ 
    foreach(array_diff(scandir($d,1),array('.','..')) as $f)if(is_file($d.'/'.$f)&&(($x)?ereg($x.'$',$f):1))$l[]=$f; 
    return $l; 
} 

$arr = file_list("../download/",".zip"); 

$filename = $arr[0]; 
$filepath = "http://".$_SERVER['SERVER_NAME']."/download/".$arr[0]; 
print($filepath); 

을, 나는 제대로 링크를 얻을 수있는 BufferedReader로 사용

private String getZipURL(){ 
    String result = ""; 
    InputStream is = null; 
    try{ 
     String url = ZipURL; 
     HttpPost httppost = new HttpPost(url); 
     HttpParams httpParameters = new BasicHttpParams(); 

     int timeoutConnection = 3000; 
     HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); 

     int timeoutSocket = 3000; 
     HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); 

     DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); 

     HttpResponse response = httpclient.execute(httppost); 
     HttpEntity entity = response.getEntity(); 
     is = entity.getContent(); 
    }catch(Exception e){ 
     Log.e("getZipURL", "Error in http connection "+e.toString()); 
     return null; 
    } 

    try{ 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
     is.close(); 

     result=sb.toString(); 
     return result; 
    }catch(Exception e){ 
     Log.e("convertZipURL", "Error converting result "+e.toString()); 
     return null; 
    } 
} 

내가보기에 잘못되었을 수도 있지만 제대로 작동합니다. 나는 같은 문제를 가진 누군가를위한 해결책을 얻을 수 있도록 코드를 게시했다. 감사!

관련 문제