简体   繁体   English

文件是部分从Webview Android下载的

[英]File is partly downloaded from Webview Android

I getting issue while downloading a PDF file on click of button click in webview. 在单击Webview中的按钮单击时下载PDF文件时遇到问题。

File is downloaded but the file is partly downloaded that's why i am getting below error 已下载文件,但部分下载了文件,这就是为什么我遇到以下错误

"The document cannot be opened because it is not a valid PDF document" “无法打开文档,因为它不是有效的PDF文档”

Below is Asyncetask activity of my to download file: 以下是我要下载文件的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;

             }

         }

     }

Friends I am stuck on this, Please help me out. 朋友,我对此感到困惑,请帮助我。

Hope this will help you. 希望这会帮助你。 I tested this code and this is working fine. 我测试了这段代码,这工作正常。

@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;

        }

EDITED: 编辑:

Extend your class from AsyncTask<String, Integer, String> and override its' methods. AsyncTask<String, Integer, String>扩展您的类AsyncTask<String, Integer, String>并覆盖其''方法。 ` `

  • onPreExecute() used to do process before start the download. onPreExecute()用于在开始下载之前进行处理。
  • doInBackground(String... params) used to do the process while downloading the file. doInBackground(String... params)用于在下载文件时执行此过程。 The above code is for this method. 上面的代码就是针对这种方法的。
  • onProgressUpdate(Integer... progress) used to do setting the progress bar according to the current download percentage. onProgressUpdate(Integer... progress)用于根据当前下载百分比设置进度条。 Once you use publishProgress (), this method will invoke. 一旦使用publishProgress(),此方法将被调用。

  • onPostExecute(String file_url) This method can used to dismiss the dislog after the file was downloaded. onPostExecute(String file_url)此方法可用于在文件下载后关闭该注销。

So what you have to do is set your progress bar to update according to the downloading percentage inside onProgressUpdate (Integer... progress) . 因此,您需要做的是将进度条设置为根据onProgressUpdate (Integer... progress)的下载百分比进行更新。 You can use setProgress() method for that. 您可以为此使用setProgress()方法。

I hope now you understand the process well :) 我希望你现在对这个过程很了解:)

This might not be an issue, but your while loop isn't correct: 这可能不是问题,但是您的while循环不正确:

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

The BufferedInputStream.read() returns a -1 when it reaches the end of the stream. BufferedInputStream.read()在到达流的末尾时返回-1

Rather, your terminating condition should be: 相反,您的终止条件应为:

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

I hope this helps. 我希望这有帮助。

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

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