2012-10-29 5 views
2

채팅에서 .pdf 파일을 받고 있는데 다운로드하고 Acrobat Reader를 사용하여 표시하려고합니다. 다음은 내 코드입니다안드로이드 다운로드 및 표시 URL :

public void showPDF(String pdf) 
     { 
      try 
      { 
       Log.i("pic", " * * * in showPdf" + pdf); 

       String extStorageDirectory = Environment.getExternalStorageDirectory().toString(); 
       File folder = new File(extStorageDirectory, "pdf"); 
       folder.mkdir(); 
       String pdf_name = pdf.replace(".pdf", ""); 
       pdf_name = pdf_name.replace("/fileupload/data/chat/", ""); 
       File file = new File(folder, pdf_name + ".pdf"); 
       try 
       { 
        file.createNewFile(); 
       } 
       catch (IOException e1) 
       { 
        e1.printStackTrace(); 
       } 
       Log.i("pic", " * * * ready to download"); 
       new DownloadFile(file, Functions.getServiceProtocol() + Functions.getServiceDomain() + pdf, pdf_name).execute(); 
      } 
      catch (Exception e) 
      { 
       Log.i("pic", " CATCH * * * in showPdf"); 
      } 
     } 
     } 



    private class DownloadFile extends AsyncTask<String, Integer, String> 
     { 
      private String fileURL, pdfname; 
      private File directory; 
      private ProgressDialog dlg = new ProgressDialog(CameraWebview.this); 

      public DownloadFile(File d, String f, String n) 
      { 
       directory = d; 
       fileURL = f; 
       pdfname = n; 
      } 

      @Override 
      protected String doInBackground(String... sUrl) 
      { 
       try 
       { 
        Log.i("pic", " TRY * * * download file"); 
        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]; 
        long total = 0; 
        int count; 

        while ((count = in.read(buffer)) != -1) { 
         total += count; 
         f.write(buffer, 0, count); 
        } 

        f.flush(); 
        f.close(); 

        try 
        { 
         Log.i("pic", " TRY * * * calling displayPdf"); 
         displayPdf(pdfname); 
        } 
        catch(Exception ex) 
        { 
         Log.i("pic", " CATCH * * * calling displayPdf"); 
        } 
       } 
       catch (Exception e) 
       { 
       } 
       return null; 
      } 

      @Override 
      protected void onPreExecute() 
      { 
       super.onPreExecute(); 
       dlg.setMessage("Downloading File ..."); 
       dlg.show(); 
      } 

      @Override 
      protected void onProgressUpdate(Integer... progress) 
      { 
       super.onProgressUpdate(progress); 
       mProgressDialog.setProgress(progress[0]); 
      } 

      @Override 
      protected void onPostExecute(String result) 
      { 
       super.onPostExecute(result); 
       if (dlg.isShowing()) 
        dlg.dismiss(); 
      } 
     } 

     public void displayPdf(String pdf_name) 
     { 
      try 
      { 
       Log.i("pic", " TRY * * * ready to show pdf"); 
       File file = new File(Environment.getExternalStorageDirectory() + "/pdf/" + pdf_name + ".pdf"); 
       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); 
       Log.i("pic", " TRY * * * here is the pdf"); 
      } 
      catch (Exception e) 
      { 
       Log.i("pic", " CATCH * * * show pdf file" + e.toString()); 
      } 

항상 "손상된 파일"이라고 말합니다. 내가 사용하고있는 URL을 확인했는데 괜찮습니다. 또한 내 애플 리케이션 아이스크림 Sandwitch입니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까 ?

+0

나는 displayPdf에서 새 File 객체를 만드는 이유를 모르겠다. 원래 파일을 사용하지 않는 이유는 무엇입니까? – njzk2

+0

도 디바이스의 파일을 보셨습니까? – njzk2

+0

예, alwya 20KB 파일이 손상 되었습니까? – user200658

답변

1

DownloadFile(File d, String f, String n)으로 전화 할 때 디렉터리를 어떻게 구합니까?

getExternalStorageDirectory (귀하가있는 것으로 가정)을 사용하는 경우 해당 pdf는 귀하의 신청서에 비공개이며 다른 신청서에서는 액세스 할 수 없습니다.

당신이 당신의 응용 프로그램에 개인이 파일을 유지하고, 또 다른 응용 프로그램을 사용하여 열 수 있도록해야 할 경우 공유 디렉토리에이 파일을 유지할 수 있다면, 당신은 얻을 getExternalStoragePublicDirectory()를 사용해야하는 ContentProvider

를 사용 파일을 저장하고 나중에 파일 URI를 검색하는 경로.

이 문제는 this과 관련이 있으므로 비슷한 대답입니다.

showPDF 내부 :

String extStorageDirectory = Environment.getExternalStoragePublicDirectory(
     Environment.DIRECTORY_DOWNLOADS).toString(); 

당신은 ("GET") setRequestMethod 후 (참)하려면 setDoOutput를 사용하는

File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/pdf/" + pdf_name + ".pdf"); 
+0

코드를 편집했습니다 – user200658

+0

내 대답을 편집했습니다. 도움이되는지 확인하십시오. – Marcelo

+0

확인. 내가 그것을 시도하자. – user200658

1

displayPdf 내부

문제를 해결해야한다.

setDoOutput (true)는 요청 메소드를 POST에 자동으로 설정합니다.

0
     theurl = new URL(url);      
         InputStream in = null; 
         File dst = new File(Environment.getExternalStorageDirectory()+"/file.pdf"); 
          try { 
           in = theurl.openStream(); 
          } catch (IOException e) { 
           // TODO Auto-generated catch block 
           e.printStackTrace(); 
          }    
          OutputStream out = null; 
         try { 
          out = new FileOutputStream(dst); 
         } catch (FileNotFoundException e) { 
          // TODO Auto-generated catch block 
         } 
          // Transfer bytes from in to out 
          try { 
           byte[] buf = new byte[100000]; 
           int len; 
          while ((len = in.read(buf)) > 0) { 
           out.write(buf, 0, len); 
          } 
         } catch (IOException e) { 
          // TODO Auto-generated catch block 
          e.printStackTrace(); 
         } 
          try { 
          in.close(); 
         } catch (IOException e) { 
          // TODO Auto-generated catch block 
          e.printStackTrace(); 
         } 
          try { 
          out.close(); 
         } catch (IOException e) { 
          // TODO Auto-generated catch block 
          e.printStackTrace(); 
         } 
관련 문제