Android下载Zip(可以在服务器上更改名称)


Android Download Zip (That can change name on the server)

我正试图让android使用php页面从我的web服务器下载一个zip文件。

如果我使用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,非常棒!

现在,在Android端,它像预期的那样下载,但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。

提前谢谢。

好吧,我使用php解决了这个问题,并使用以下脚本将zip的链接动态写入屏幕:

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);

然后在android上,我使用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;
    }
}

这看起来可能是错误的,但它如我所愿。我发布了代码,这样我就可以为有同样问题的人找到解决方法。谢谢