简体   繁体   English

如何从服务器下载pdf文件,将其存储在sdcard中,并通过android中的intent查看?

[英]how to download pdf file from server , store it in sdcard and view through intent in android?

I have written a program to download my pdf file from server into my sdcard , which is getting downloaded properly but when i am viewing it through my pdfviewer it says unable to open this file. 我已经编写了一个程序,可以将服务器上的pdf文件下载到sdcard,该文件可以正确下载,但是当我通过pdfviewer查看该文件时,它无法打开该文件。 Also the files size is 4.5mb , but the pdf which is getting downloaded into my sdcards pdf folder has size 0 . 另外,文件大小为4.5mb,但是要下载到我的sdcards pdf文件夹中的pdf的大小为0。

private void processPDF(String subject_pdf) {
    new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... params) {
            String result = "";
            StringBuilder builder = new StringBuilder(100000);
            try {
                String URL = 
                "http://192.168.1.3:8082/APP_Server/subject_pdfs_result.jsp? 
                 branch_year="+ type; //type = branches(e.g computers , IT) 
                HttpClient httpclient = new DefaultHttpClient();
                HttpGet httpget = new HttpGet(URL);
                HttpResponse response = httpclient.execute(httpget);
                InputStream is = response.getEntity().getContent();
                BufferedReader buffer = new BufferedReader(new 
                InputStreamReader(is));
                // result = is.toString();
                while ((result = buffer.readLine()) != null) {
                    builder.append(result);
                }

            } catch (Exception ex) {
                ex.printStackTrace();

            }
            return builder.toString().replaceAll("\\<.*?\\>", "");
        }

        @Override
        protected void onPostExecute(String builder) {
            //url has the pdf name 
            name= builder.replace("\t", "");
            image_url = 
            "http://192.168.1.3:8082/APP_Server/Images/Books_Pdf/" + url;
            extStorageDirectory = 
            Environment.getExternalStorageDirectory().toString();
            File folder = new File(extStorageDirectory, "pdf");
            folder.mkdir();
            File file = new File(folder, name);
            try {
                file.createNewFile();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            PDFDownloader.DownloadFile(image_url, file);

            showPdf();

        }

    }.execute(null, null, null);

}

private void showPdf() {
    File file = new File(Environment.getExternalStorageDirectory() + "/pdf/" 
               + name);
    PackageManager packageManager = getPackageManager();
    Intent testIntent = new Intent(Intent.ACTION_VIEW);
    testIntent.setType("application/pdf");
    List list = packageManager.queryIntentActivities(testIntent, 
    PackageManager.MATCH_DEFAULT_ONLY);
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    Uri uri = Uri.fromFile(file);
    intent.setDataAndType(uri, "application/pdf");
    startActivity(Intent.createChooser(intent, "Open File"));

}

PDFDownloader.java PDFDownloader.java

public static void DownloadFile(String fileURL, File directory) {
    try {
        FileOutputStream f = new FileOutputStream(directory);
        URL u = new URL(fileURL);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setDoOutput(true);
        c.connect();

        InputStream in = c.getInputStream();

        byte[] buffer = new byte[1024];
        int len1 = 0;
        while ((len1 = in.read(buffer)) > 0) {
            f.write(buffer, 0, len1);
        }
        f.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

Please need some guidance as to where i am going wrong. 关于我要去哪里,请需要一些指导。 Thank You. 谢谢。

work as this code that i insert it work for me 就像我插入的这段代码一样为我工作

public class Tapir extends ListActivity {

// flag for Internet connection status
Boolean isInternetPresent = false;

// Connection detector class
ConnectionDetector cd;

public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
 private ProgressDialog  mProgressDialog;
 public  MediaPlayer    mp;

 private String       URLDwnTapir="http://internetwan.xzn.ir/tapir_vocalisation.mp3";
 private String       URLDwnTapir_pic="http://internetwan.xzn.ir/tapir.jpg";

 File sdcard=Environment.getExternalStorageDirectory();
 File dir=new File(sdcard.getAbsolutePath()+"/WorldOfSounds/Tapir");
 //Objects of files
 File Tapir_obj=new File(dir,"Tapir.mp3");

 File Tapir_PIC_obj=new File(dir,"Tapir.jpg");


 String   Tapir=Environment.getExternalStorageDirectory().getAbsolutePath()+"/WorldOfSounds/Tapir/Tapir.jpg";
 @Override
    public void onBackPressed() {
        super.onBackPressed();
        if(mp!=null&&mp.isPlaying()){
            mp.release();
            mp.stop();
        }
    }

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.tapir);

    setListAdapter (new ArrayAdapter  <String> (this,
            android.R.layout.simple_list_item_1,
            getResources ().getStringArray(R.array.Tapir_value)));

    // creating connection detector class instance
    cd = new ConnectionDetector(getApplicationContext());


}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    // TODO Auto-generated method stub
    super.onListItemClick(l, v, position, id);
    switch(position){
    case 0:
         if(!dir.exists()){
                dir.mkdirs();
            }
         if(Tapir_obj.exists()){
                if(mp!=null){
                    mp.release();
                }if(Tapir_PIC_obj.exists()){
                    LinearLayout linl=(LinearLayout)findViewById(R.id.LinearLayout1);
                    //FileInputStream streamIn = new FileInputStream(Tapir_PIC_obj);
                    //Bitmap bitmap = BitmapFactory.decodeStream(streamIn);
                    //Uri  imgUri=Uri.fromFile(Tapir_PIC_obj);

                    BitmapDrawable d = new BitmapDrawable(Tapir);
                    linl.setBackgroundDrawable(d);


                }else{
                    StartDwnTapir_pic();
                }


                final AudioManager mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
                final int originalVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
                mp = new MediaPlayer();
                mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mp=MediaPlayer.create(null, Uri.fromFile(Tapir_obj)) ;  
                mp.start();
                mp.setOnCompletionListener(new OnCompletionListener()
                {
                   @Override
                   public void onCompletion(MediaPlayer mp)
                   {
                      mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, originalVolume, 0);
                   }
                });

                //LinearLayout linl=(LinearLayout)findViewById(R.id.LinearLayout1);
                //linl.setBackgroundResource(R.drawable.tapir);

            }else{
                // get Internet status
                isInternetPresent = cd.isConnectingToInternet();

                // check for Internet status
                if (isInternetPresent) {
                    // Internet Connection is Present
                    // make HTTP requests
                    startDwnTapir_obj();

                } else {
                    // Internet connection is not present
                    // Ask user to connect to Internet
                    Toast.makeText(this,"مشکل در اتصال به شبکه اینترنت!",Toast.LENGTH_LONG).show();

                }



            }//end else

            //Toast.makeText(this,"you selected position 0",Toast.LENGTH_LONG).show();
            break;
    }//end switch

}//end onlistitem

private void startDwnTapir_obj(){

    new DwnstartDwnTapir_objAsync().execute(URLDwnTapir);       

                                }

private void StartDwnTapir_pic(){

    new StartDwnTapir_picAsync().execute(URLDwnTapir_pic);      

                                }



 @Override
    protected Dialog onCreateDialog(int id) {
         //String SmallFountain = URLDownloadSmallFountain.substring(URLDownloadSmallFountain.lastIndexOf('/') + 1, URLDownloadSmallFountain.length());
           // String msg="downloading file : "+SmallFountain;
        switch (id) {
                    case DIALOG_DOWNLOAD_PROGRESS:

                mProgressDialog = new ProgressDialog(this);

                mProgressDialog.setMessage("downloading file... \n Please wait");

                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

                mProgressDialog.setCancelable(false);

                mProgressDialog.show();

                return mProgressDialog;

            default:

                return null;

        }

    }//end onCreatDialog

 class DwnstartDwnTapir_objAsync extends AsyncTask<String, String, String> {

        @Override
           protected void onPreExecute() {

               super.onPreExecute();

               showDialog(DIALOG_DOWNLOAD_PROGRESS);

           }



        @Override
           protected String doInBackground(String... aurl) {

               int count;

               try {

                   URL URLDwnTapir = new URL(aurl[0]);

                   HttpURLConnection conexion = (HttpURLConnection) URLDwnTapir.openConnection();

                   conexion.connect();

                   int lenghtOfFile = conexion.getContentLength();

                   Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

                   InputStream input = new BufferedInputStream(URLDwnTapir.openStream());

                  if(!dir.exists()){
                   dir.mkdirs();
                  }           

                   OutputStream output = new FileOutputStream(Tapir_obj);

                   byte data[] = new byte[1024];

                   long total = 0;

                   while ((count = input.read(data)) != -1) {

                       total += count;

                       publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                       output.write(data, 0, count);

                   }
                   Log.d("ANDRO_ASYNC", "end download Tapir_obj File ");

                   output.flush();

                   output.close();

                   input.close();

               }
               catch (Exception e) {}

               return null;

           }



           @Override
           protected void onProgressUpdate(String... progress) {

               Log.d("ANDRO_ASYNC", progress[0]);

               mProgressDialog.setProgress(Integer.parseInt(progress[0]));

           }



        @Override
           protected void onPostExecute(String unused) {

               dismissDialog(DIALOG_DOWNLOAD_PROGRESS);

           }


       }//end Class DwnTapirAsync 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM