文件部分从Webview Android下载

时间:2014-02-16 22:51:21

标签: java android webview pdf-generation android-webview

我在点击webview中的按钮点击下载PDF文件时遇到问题。

文件已下载,但文件已部分下载,这就是我收到以下错误的原因

“无法打开文档,因为它不是有效的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;

             }

         }

     }

朋友我被困在这,请帮助我。

2 个答案:

答案 0 :(得分: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()方法。

我希望你现在能理解这个过程:)

答案 1 :(得分: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);

我希望这会有所帮助。