2014-02-16 91 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并调用它的方法。我更新了我的答案,以便让你更清楚。我希望你现在有了路。 –