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

标签 java php android

我正在尝试让 android 使用 php 页面从我的网络服务器下载 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;
    }
}

这可能看起来是错误的,但它按我想要的方式工作。我发布了代码,这样我就可以为遇到同样问题的人找到解决方法。谢谢!

关于java - Android下载Zip(可以在服务器上更改名称),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9896710/

相关文章:

java - Restful服务客户端的并发请求是否会给Restful服务带来问题?

java - 在 Mac 上设置 JAVA_HOME

java - 如何得知DJ原生swing jwebbrowser已经完全加载网页了?

php - 用户交互式刷新动态菜单

php - 如何从带有分页符的表格中正确生成PDF

java - 线程 "main"java.lang.NullPointerException 中出现异常,但 int 在 main 方法中解析

php - mysql php 中的 SQL 存储过程

android - 使用DrawingCache 屏幕截图TextureView 为黑色

Android对齐表格的内容

android - 可以在 iOS/Android 的 fragment 着色器中使用 highp 吗?