Java 文件部分从Webview Android下载

Java 文件部分从Webview Android下载,java,android,webview,pdf-generation,android-webview,Java,Android,Webview,Pdf Generation,Android Webview,我在webview中单击按钮下载PDF文件时遇到问题 文件已下载,但文件已部分下载,这就是为什么我得到下面的错误 “无法打开该文档,因为它不是有效的PDF文档” 下面是我的下载文件的Asyncetask活动: public class DownloadPDFTask extends AsyncTask<String, Void, Integer> { protected ProgressDialog mWorkingDialog; // prog

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

             }

         }

     }
公共类下载PDFTASK扩展异步任务
{
受保护的ProgressDialog mWorkingDialog;//进度对话框
受保护的字符串mFileName;//下载的文件
受保护的字符串mError;//用于查找错误
@凌驾
受保护的整数doInBackground(字符串…URL)
{
字符串filename=“”;
字符串str[]=URL[2]。拆分(“;”);
字符串st[]=str[1]。拆分(“”);
filename=st[1];
字符串extStorageDirectory=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_下载).toString();
File myDir=新文件(extStorageDirectory,“NCR”);
File File=新文件(extStorageDirectory+“/NCR/”+文件名);
//如果目录不存在,请创建该目录
如果(!myDir.exists())
myDir.mkdirs();
if(file.exists()){
System.out.println(“内部文件存在”);
delete();
}
尝试
{
字节[]数据缓冲=新字节[4096];
int nRead=0;
mFileName=文件名;
System.out.println(“mFileName”+mFileName);
//下载URL并存储到strFileName
//连接到url
java.net.URL urlReport=新的java.net.URL(URL[0]);
URLConnection urlConn=urlReport.openConnection();
setRequestProperty(“用户代理”,URL[1]);
setRequestProperty(“内容处置”,URL[2]);
setRequestProperty(“内容类型”、“应用程序/pdf”);
urlConn.setRequestProperty(“接受”,“*/*”);
InputStreamInput=urlReport.openStream();
BufferedInputStream bufferedStreamInput=新的BufferedInputStream(streamInput,8192);
FileOutputStream outputStream=新的FileOutputStream(extStorageDirectory+“/NCR/”+mFileName);
而((nRead=bufferedStreamInput.read(dataBuffer))>0)
write(dataBuffer,0,nRead);
streamInput.close();
outputStream.close();
//显示PDF(mFileName);
}
捕获(例外e)
{
Log.e(“myApp”,e.getMessage());
mError=e.getMessage();
申报表(1);
}
返回(0);
}
@凌驾
受保护的void onPreExecute()
{
//显示“正在下载,请稍候”对话框
mWorkingDialog=ProgressDialog.show(上下文“,”正在下载PDF文档,请稍候…”,true);
返回;
}
@凌驾
受保护的void onPostExecute(整数结果)
{
if(mWorkingDialog!=null)
{
mWorkingDialog.Disclose();
mWorkingDialog=null;
}
开关(结果)
{
案例0://一个URL
尝试
{
显示PDF(mFileName);
}
捕获(ActivityNotFounde异常)
{
Toast.makeText(上下文,“未安装PDF查看器”,Toast.LENGTH_LONG.show();
}
打破
案例1://错误
Toast.makeText(上下文、mError、Toast.LENGTH_LONG).show();
打破
}
}
}

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

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

我希望这对你有帮助。

希望这对你有帮助。我测试了这段代码,效果很好

@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
扩展类并重写其“方法”。 `

  • onPreExecute()
    用于在开始下载之前执行此过程
  • doInBackground(字符串…参数)
    用于在 下载文件。上面的代码用于此方法
  • onProgressUpdate(整数…进度)
    用于设置 根据当前下载百分比设置进度条。使用publishProgress()后,此方法将调用

  • onPostExecute(字符串文件\u url)
    此方法可用于解除 在文件下载后删除

因此,您需要做的是将进度条设置为根据
onProgressUpdate(Integer…progress)
中的下载百分比进行更新。您可以使用
setProgress()
方法进行此操作


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

亲爱的Zusee,你能定义publishProgress((int)((total*100)/lengthOfFile));还请尝试放置publishProgress的代码。publishProgress()来自AsyncTask。它调用onProgressUpdate(),这通常用于更新诸如ProgressBar之类的UI元素。@Altavista是的,正如ntv100所说,您必须扩展AsyncTask并调用它的方法。我更新了我的答案,让你更清楚。我希望你现在明白了。