安卓系统调用php脚本下载文件并保存在sd卡中


Android call php script to download file and save it in sd-card

我是php的新手。我尝试在安卓系统中制作一个应用程序,从eClass平台下载文件。我开发了这个脚本:

    <?php
            $code=$_GET['code'];
            $code = stripslashes($code);
            $code = mysql_real_escape_string($code);
            $filename=$_GET['filename'];
            $filename = stripslashes($filename);
            $filename = mysql_real_escape_string($filename);
            $path = "C:''xampp''htdocs''openeclass-2.5''courses''".$code."''dropbox''".$filename;
            $fullPath = $path.$_GET['download_file'];
            if ($fd = fopen ($fullPath, "r")) {
                $fsize = filesize($fullPath);
                $path_parts = pathinfo($fullPath);
                $ext = strtolower($path_parts["extension"]);
                switch ($ext) {
                    case "pdf":
                    header("Content-type: application/pdf"); // add here more headers for diff. extensions
                    header("Content-Disposition: attachment; filename='"".$path_parts["basename"]."'""); // 
            use 'attachment' to force a download
                    break;
                    default;
                    header("Content-type: application/octet-stream");
                    header("Content-Disposition: filename='"".$path_parts["basename"]."'"");
                }
                header("Content-length: $fsize");
                header("Cache-control: private"); //use this to open files directly
                while(!feof($fd)) {
                    $buffer = fread($fd, 2048);
                    echo $buffer;
                }
            }
            fclose ($fd);
            exit;
            ?>

它在从浏览器(在我的本地主机中)调用时下载文件,并在url中指定代码和文件名作为参数。现在我想在我的android应用程序中构建一个函数,调用这个脚本,获取文件并将其保存在sd卡中的某个位置

我怎样才能做到这一点?还有可能在模拟器中完成吗?提前谢谢!

不幸的是,您无法通过php强制下载图像。您需要的是创建一个类,该类将从web位置流式传输文件并将其保存到sd卡。

我的应用程序中有simmilar代码,可以同时执行以下操作:

try {
    newurl = new URL(iurl); // iurl is a String value
        b = BitmapFactory.decodeStream(newurl.openConnection().getInputStream());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } 
try {
    b.compress(CompressFormat.JPEG, 100, new FileOutputStream(
        sdcard_image)); // sdcard_image is a String value of local filename (including dir)
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    }

希望这能帮助