2015-11-03 96 views
-1

我創建了一個用於從服務器下載pdf的php代碼,它工作良好。現在我想在android id應用中使用這個php文件,並從android中的服務器下載pdf。我如何做到這一點?我的php代碼:從android服務器中的php服務器下載pdf

<?php 
$id = $_GET['bookid']; 
$sql = "SELECT file,BookName FROM books WHERE id=" . prepareSQL($id) . " "; 

$query = mysql_query($sql) or die('Error, query failed'); 
$content = mysql_fetch_array($query); 

header("Content-length: $size"); 
header("Content-type: $type"); 
$name=$content['BookName']; 
header("Content-Disposition: attachment; filename=$name"); 

echo $content['file']; 
?> 

回答

0

您可以使用它。

public static void downloadAndOpenPDF(final Context context, final String pdfUrl) { 
    // Get filename 
    final String filename = pdfUrl.substring(pdfUrl.lastIndexOf("/") + 1); 
    // The place where the downloaded PDF file will be put 
    final File tempFile = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), filename); 
    if (tempFile.exists()) { 
     // If we have downloaded the file before, just go ahead and show it. 
     openPDF(context, Uri.fromFile(tempFile)); 
     return; 
    } 

    // Show progress dialog while downloading 
    cm=new CustomLoaderDialog(context); 
    cm.show(true); 
    //final ProgressDialog progress = ProgressDialog.show(context, "AIH" , "Please Wait", true); 

    // Create the download request 
    DownloadManager.Request r = new DownloadManager.Request(Uri.parse(pdfUrl)); 
    r.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS,filename); 
    final DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); 
    BroadcastReceiver onComplete = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      if (!cm.isShowing()) { 
       return; 
      } 
      context.unregisterReceiver(this); 

      cm.hide(); 
      long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1); 
      Cursor c = dm.query(new DownloadManager.Query().setFilterById(downloadId)); 

      if (c.moveToFirst()) { 
       int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS)); 
       if (status == DownloadManager.STATUS_SUCCESSFUL) { 
        openPDF(context, Uri.fromFile(tempFile)); 
       } 
      } 
      c.close(); 
     } 
    }; 
    context.registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); 

    // Enqueue the request 
    dm.enqueue(r); 
}