2014-02-16 124 views
0

我在點擊webview中的按鈕點擊下載PDF文件時出現問題。文件部分從Webview下載Android

文件下載,但該文件部分下載的,這就是爲什麼我得到以下錯誤

「的文件無法打開,因爲它不是一個有效的PDF文件」

下面是Asyncetask活動我要下載的文件:

public class DownloadPDFTask extends AsyncTask<String, Void, Integer> 
    { 
     protected ProgressDialog mWorkingDialog; // progress dialog 
     protected String mFileName;   // downloaded file 
     protected String mError;   // for errors 

     @Override 
     protected Integer doInBackground(String... urls) 
     { 
      String filename = ""; 
      String str[] = urls[2].split(";"); 
      String st[] =str[1].split("="); 
      filename = st[1]; 
      String extStorageDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString(); 
       File myDir = new File(extStorageDirectory, "NCR"); 

       File file = new File(extStorageDirectory+"/NCR/"+filename);  
        // create the directory if it does not exist 
        if (!myDir.exists()) 
         myDir.mkdirs(); 

        if (file.exists()) { 
         System.out.println("INSIDE FILE EXIST"); 
         file.delete(); 
        } 
      try 
      { 
      byte[] dataBuffer = new byte[4096]; 
       int nRead = 0; 

       mFileName = filename; 

       System.out.println("mFileName<><><> " +mFileName); 
       // download URL and store to strFileName 

       // connection to url 
       java.net.URL urlReport = new java.net.URL(urls[0]); 
       URLConnection urlConn = urlReport.openConnection(); 
       urlConn.setRequestProperty("User-Agent", urls[1]); 
       urlConn.setRequestProperty("Content-Disposition", urls[2]); 
       urlConn.setRequestProperty("Content-Type", "application/pdf"); 
       urlConn.setRequestProperty("Accept", "*/*"); 
       InputStream streamInput = urlReport.openStream(); 
       BufferedInputStream bufferedStreamInput = new BufferedInputStream(streamInput,8192); 
       FileOutputStream outputStream = new FileOutputStream(extStorageDirectory+"/NCR/"+mFileName); 
       while ((nRead = bufferedStreamInput.read(dataBuffer)) > 0) 
        outputStream.write(dataBuffer, 0, nRead); 
       streamInput.close(); 
       outputStream.close(); 
//    displayPdf(mFileName); 

      } 
      catch (Exception e) 
      { 
      Log.e("myApp", e.getMessage()); 
      mError = e.getMessage(); 
      return (1); 
      } 

      return (0); 
     } 



     @Override 
     protected void onPreExecute() 
     { 
      // show "Downloading, Please Wait" dialog 
      mWorkingDialog = ProgressDialog.show(context, "", "Downloading PDF Document, Please Wait...", true); 
      return; 
     } 



     @Override 
     protected void onPostExecute (Integer result) 
     { 
       if (mWorkingDialog != null) 
      { 
      mWorkingDialog.dismiss(); 
      mWorkingDialog = null; 
      } 

       switch (result) 
       { 
       case 0:       // a URL 
       try 
       { 

        displayPdf(mFileName); 
       } 
       catch (ActivityNotFoundException e) 
       { 
        Toast.makeText(context, "No PDF Viewer Installed", Toast.LENGTH_LONG).show(); 
       } 

       break; 

      case 1:       // Error 

       Toast.makeText(context, mError, Toast.LENGTH_LONG).show(); 
       break; 

      } 

     } 

    } 

朋友我被困在這,請幫幫我。

回答

0

這可能不是一個問題,但你的while循環是不正確的:

while ((nRead = bufferedStreamInput.read(dataBuffer)) > 0) 
        outputStream.write(dataBuffer, 0, nRead); 

BufferedInputStream.read()當到達流的末尾返回-1

相反,你的終止條件應該是:

while ((nRead = bufferedStreamInput.read(dataBuffer)) != -1) 
        outputStream.write(dataBuffer, 0, nRead); 

我希望這有助於。

1

希望這會幫助你。我測試了這個代碼,這工作正常。

@Override 
     protected String doInBackground(String... params) { 
      // TODO Auto-generated method stub 
      int count; 
      try{ 
       URL url=new URL(params[0]); 
       URLConnection connection=url.openConnection(); 
       connection.connect(); 
       //getting file length 
       long lengthOfFile=connection.getContentLength(); 
       //input stream to read file with 8k buffer 
       InputStream input=new BufferedInputStream(url.openStream(),8192); 
       //out stream to write file 
       OutputStream output=new FileOutputStream(Environment.getExternalStorageDirectory()+"/Download/Test/software_testing.pdf"); 

       byte data[]= new byte[1024]; 
       long total =0; 
       while ((count = input.read(data)) != -1){ 
        if(isCancelled()) 
         return null; 
        total +=count; 
        //publishing the progress 
        //After this onProgressUpdate will be called 
        if(lengthOfFile > 0){ 
         //System.out.println((int)((total*100)/lengthOfFile)+"First Line"); 
         //Call onProgressUpdate() for display status 
         publishProgress((int)((total*100)/lengthOfFile)); 

        } 

        //writing data to file 
        output.write(data,0,count); 
       } 
       //flushing output 
       output.flush(); 
       //closing stream 
       output.close(); 
       input.close(); 

      }catch(Exception e){ 
       Log.e("Error", e.getMessage()); 
       System.out.println("Exception :"+e.getMessage()); 
      } 

      return null; 

     } 

編輯:

AsyncTask<String, Integer, String>擴展您的類並覆蓋其方法。 `

  • onPreExecute()用於開始下載之前的過程。
  • doInBackground(String... params)用於做這個過程,而 下載文件。以上代碼適用於此方法。
  • onProgressUpdate(Integer... progress)用於根據當前下載百分比設置 進度條。一旦你使用publishProgress(),這個方法就會調用。

  • onPostExecute(String file_url)該方法可用於在文件下載完成後關閉 dislog。

所以你要做的是設置你的進度條根據下載百分比onProgressUpdate (Integer... progress)內更新。您可以使用setProgress()方法。

我希望現在你瞭解的過程以及:)

+0

親愛Zusee,請你定義publishProgress((INT)((總* 100)/ lengthOfFile)); 請同時嘗試爲publisProgress放置代碼。 – Altavista

+1

publishProgress()來自AsyncTask。它調用onProgressUpdate(),它經常用來更新像ProgressBar這樣的UI元素。 – ntv1000

+0

@Altavista是的,因爲ntv100表示​​您必須擴展AsyncTask並調用它的方法。我更新了我的答案,以便讓你更清楚。我希望你現在有了路。 –