【问题标题】:File is partly downloaded from Webview Android文件部分从 Webview Android 下载
【发布时间】:2014-02-16 22:51:21
【问题描述】:

我在点击 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;

             }

         }

     }

朋友们,我被困在这个问题上,请帮帮我。

【问题讨论】:

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


    【解决方案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&lt;String, Integer, String&gt; 扩展你的类并覆盖它的方法。 `

    • onPreExecute() 用于在开始下载之前进行处理。
    • doInBackground(String... params) 用来做这个过程,而 下载文件。上面的代码就是针对这个方法的。
    • onProgressUpdate(Integer... progress) 用于设置 根据当前下载百分比的进度条。一旦你使用了 publishProgress(),这个方法就会被调用。

    • onPostExecute(String file_url) 这个方法可以用来关闭 下载文件后退出日志。

    所以你要做的就是设置你的进度条根据onProgressUpdate (Integer... progress)里面的下载百分比更新。您可以为此使用setProgress() 方法。

    我希望你现在很好地理解了这个过程:)

    【讨论】:

    • 亲爱的 Zusee,请您定义 publishProgress((int)((total*100)/lengthOfFile));也请尝试为 publisProgress 输入代码。
    • publishProgress() 来自 AsyncTask。它调用 onProgressUpdate(),通常用于更新像 ProgressBar 这样的 UI 元素。
    • @Altavista 是的,正如 ntv100 所说,您必须扩展 AsyncTask 并调用它的方法。我更新了我的答案,让你更清楚。我希望你现在明白了。
    【解决方案2】:

    这可能不是问题,但您的 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);
    

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2014-03-18
      • 1970-01-01
      • 1970-01-01
      • 2014-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-27
      相关资源
      最近更新 更多