2017-04-06 100 views
3

将pdf文件上传到firebase存储后,我上传了一个PDF文件到firebase存储,我正在下载url。现在我想在我的应用程序中从这个下载网址打开PDF文件。打开存储在Firebase存储中的pdf文件url

下面是将pdf文件上传到firebase存储后获得的网址。

https://firebasestorage.googleapis.com/v0/b/realtime-chat-46f4c.appspot.com/o/documents%2Fbf307aa5-79ae-4532-8128-ee394537b357.pdf?alt=media&token=2d0c5329-4717-4adc-9418-6614913e5bfa

现在我想开一个意图查看此pdf文件,我用下面的代码是:

String url = "https://firebasestorage.googleapis.com/v0/b/realtime-chat-46f4c.appspot.com/o/documents%2Fbf307aa5-79ae-4532-8128-ee394537b357.pdf?alt=media&token=2d0c5329-4717-4adc-9418-6614913e5bfa"; 

Intent intent = new Intent(android.content.Intent.ACTION_VIEW); 
intent.setDataAndType(Uri.parse(url), "application/pdf"); 
startActivity(Intent.createChooser(intent, "Choose an Application:")); 

我的手机有应用,这可以打开这个pdf文件,它仍然说没有安装应用程序来查看这个文件。

如果我在File中转换这个URL并使用下面的代码,那么应用程序的选择器会被打开,但它会报错,无法打开文件。

Intent intent = new Intent(android.content.Intent.ACTION_VIEW); 
File file = new File(name); 
intent.setDataAndType(Uri.fromFile(file), "aplication/pdf"); 

我见过很多答案,说先下载文件然后打开它,但我不想下载文件,我只是想查看它。

如果有人对此有任何想法,请帮助我。

非常感谢先进的。

+0

当你说“它给出的错误,该文件无法打开”,你能有更多的具体说明吗?你在一些日志中看到这个吗?请准确显示您所看到的内容。 –

回答

-2

使用网页视图用于查看PDF文件 -

WebView webview = (WebView) findViewById(R.id.webview); 
    webview.getSettings().setJavaScriptEnabled(true); 
    String pdf = "https://firebasestorage.googleapis.com/v0/b/realtime-chat-46f4c.appspot.com/o/documents%2Fbf307aa5-79ae-4532-8128-ee394537b357.pdf?alt=media&token=2d0c5329-4717-4adc-9418-6614913e5bfa"; 
    webview.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf); 
+0

这是一个选项,但我不想在Webview中查看PDF文件。我的要求是在安装的pdf查看器中使用intent来打开pdf文件。请帮助我如何实现这一目标。谢谢 –

+1

你甚至试过这个吗?这种使用谷歌pdf查看器加载远程PDF的方式甚至不起作用,它说“无法预览”。 –

1

请下列文件/方法添加到您的项目

  1. PdfDownloader.java
  2. PDFDownloaderAsyncTask.java

然后使用以下方法handleViewPdf查看PDF:

private void handleViewPdf() { 

    File folder = getAppDirectory(context); 
    String fileName = "test.pdf";// getPdfFileName(pdfUrl); 
    File pdfFile = new File(folder, fileName); 

    if (pdfFile.exists() && pdfFile.length() > 0) { 
     openPDFFile (context, Uri.fromFile(pdfFile)); 
    } 
    else { 
     if (pdfFile.length() == 0) { 
      pdfFile.delete(); 
     } 
     try { 
      pdfFile.createNewFile(); 
     } 
     catch (IOException e) { 
      e.printStackTrace(); 
     } 
     ArrayList<String> fileNameAndURL = new ArrayList<>(); 
     fileNameAndURL.add (pdfFile.toString()); 
     fileNameAndURL.add (pdfUrl); 
     fileNameAndURL.add (fileName); 
     if (pdfDownloaderAsyncTask == null) { 
      pdfDownloaderAsyncTask = new PDFDownloaderAsyncTask (context, pdfFile); 
     } 
     if (hasInternetConnection (context)) { 
      if (!pdfDownloaderAsyncTask.isDownloadingPdf()) { 
       pdfDownloaderAsyncTask = new PDFDownloaderAsyncTask (context, pdfFile); 
       pdfDownloaderAsyncTask.execute (fileNameAndURL); 
      } 
     } 
     else { 
      //show error 
     } 
    } 
} 

PDFDownloaderAsyncTask.java

import java.io.File; 
    import java.util.ArrayList; 

    import android.content.Context; 
    import android.net.Uri; 
    import android.os.AsyncTask; 
    import android.os.Handler; 
    import android.text.TextUtils; 
    import android.widget.Toast; 


    public class PDFDownloaderAsyncTask extends AsyncTask<ArrayList<String>, Void, String> { 

     private boolean isDownloadingPdf = false; 

     private File file; 
     private Context context; 

     public PDFDownloaderAsyncTask (Context context, File file) { 

      this.file = file; 
      this.context = context; 
      this.isDownloadingPdf = false; 
     } 

     public boolean isDownloadingPdf() { 

      return this.isDownloadingPdf; 
     } 

     @Override 
     protected void onPreExecute() { 

      super.onPreExecute(); 
      //show loader etc 
     } 

     @Override 
     protected String doInBackground (ArrayList<String>... params) { 

      isDownloadingPdf = true; 
      File file = new File (params[0].get (0)); 
      String fileStatus = PdfDownloader.downloadFile (params[0].get (1), file); 
      return fileStatus; 
     } 

     @Override 
     protected void onPostExecute (String result) { 

      super.onPostExecute (result); 
      Loader.hideLoader(); 
      if (!TextUtils.isEmpty (result) && result.equalsIgnoreCase (context.getString (R.string.txt_success))) { 
       showPdf(); 
      } 
      else { 
       isDownloadingPdf = false; 
       Toast.makeText (context, context.getString (R.string.error_could_not_download_pdf), Toast.LENGTH_LONG).show(); 
       file.delete(); 
      } 
     } 

     @Override 
     protected void onCancelled() { 

      isDownloadingPdf = false; 
      super.onCancelled(); 
      //Loader.hideLoader(); 
     } 

     @Override 
     protected void onCancelled (String s) { 

      isDownloadingPdf = false; 
      super.onCancelled (s); 
      //Loader.hideLoader(); 
     } 

     private void showPdf() { 

      new Handler().postDelayed (new Runnable() { 
       @Override 
       public void run() { 

        isDownloadingPdf = false; 
        openPDFFile (context, Uri.fromFile (file)); 
       } 
      }, 1000); 
     } 
    } 

PdfDownloader.java

package com.pdf; 

import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 

public class PdfDownloader { 
    private static final int MEGABYTE = 1024 * 1024; 

    public static String downloadFile (String fileUrl, File directory) { 

     String downloadStatus; 
     try { 

      URL url = new URL (fileUrl); 
      HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
      urlConnection.connect(); 

      InputStream inputStream = urlConnection.getInputStream(); 
      FileOutputStream fileOutputStream = new FileOutputStream (directory); 
      int totalSize = urlConnection.getContentLength(); 

      Log.d ("PDF", "Total size: " + totalSize); 
      byte[] buffer = new byte[MEGABYTE]; 
      int bufferLength = 0; 
      while ((bufferLength = inputStream.read (buffer)) > 0) { 
       fileOutputStream.write (buffer, 0, bufferLength); 
      } 
      downloadStatus = "success"; 
      fileOutputStream.close(); 
     } 
     catch (FileNotFoundException e) { 
      downloadStatus = "FileNotFoundException"; 
      e.printStackTrace(); 
     } 
     catch (MalformedURLException e) { 
      downloadStatus = "MalformedURLException"; 
      e.printStackTrace(); 
     } 
     catch (IOException e) { 
      downloadStatus = "IOException"; 
      e.printStackTrace(); 
     } 
     Log.d ("PDF", "Download Status: " + downloadStatus); 
     return downloadStatus; 
    } 


    public static void openPDFFile (Context context, Uri path) { 

     Intent intent = new Intent (Intent.ACTION_VIEW); 
     intent.setDataAndType (path, "application/pdf"); 
     intent.setFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     try { 
      context.startActivity (intent); 
     } 
     catch (ActivityNotFoundException e) { 
      Toast.makeText (context, context.getString (R.string.txt_no_pdf_available), Toast.LENGTH_SHORT).show(); 
     } 
     Loader.hideLoader(); 
    } 

    public static File getAppDirectory (Context context) { 

     String extStorageDirectory = Environment.getExternalStorageDirectory().toString(); 
     File folder = new File (extStorageDirectory, context.getString (R.string.app_folder_name).trim()); 
     if (!folder.exists()) { 
      boolean success = folder.mkdirs(); 
      Log.d ("Directory", "mkdirs():" + success); 
     } 
     return folder; 
    } 

} 
+0

感谢您的努力,但我不想下载该文件,因为我从我的设备上传文件,并且它已经存在于我的设备存储中,但在上传到Firebase存储后,我想使用存储网址将其打开。 –

+0

什么是代码中的'R.string.txt_success'? – Aradhna

+0

成功 Pehlaj

1

您应该使用意向选配

Intent intent = new Intent(Intent.ACTION_VIEW); 
intent.setDataAndType(Uri.parse(url), "application/pdf"); 
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
Intent newIntent = Intent.createChooser(intent, "Open File"); 
try { 
    startActivity(newIntent); 
} catch (ActivityNotFoundException e) { 
    // Instruct the user to install a PDF reader here, or something 
} 
+0

我已经试过这个,但是它没有打开Intent选择器,并且说没有应用程序安装来读取它,但我已经在我的设备中安装了Pdf阅读器。 –

0

您的手机未检测到PDF,因为您使用的URL是String对象而不是PDF对象。从技术上讲,除非您下载PDF,否则它不应该从手机上以PDF格式打开。手机上的PDF阅读器只有在Android操作系统告诉他们有一个有效的PDF文件后才会被激活。请看看任何PDF库的源代码,以更好地理解这一点 - >https://android-arsenal.com/tag/72?sort=created

但是,要回答你的问题,你应该尝试打开你的URL作为URL。它会激活手机上的浏览器,反过来会检测到它需要PDF阅读器并激活相应的阅读器。

喜欢的东西

String url = "https://firebasestorage.googleapis.com/v0/b/realtime-chat-46f4c.appspot.com/o/documents%2Fbf307aa5-79ae-4532-8128-ee394537b357.pdf?alt=media&token=2d0c5329-4717-4adc-9418-6614913e5bfa"; 


public void openWebPage(String url) { 
    Uri webpage = Uri.parse(url); 
    Intent intent = new Intent(Intent.ACTION_VIEW, webpage); 
    if (intent.resolveActivity(getPackageManager()) != null) { 
     startActivity(intent); 
    } 
} 

不过,我想,你只想验证,如果该文件得到了成功上传。如果手机上有本地副本,则只需打开本地副本而不是下载其他副本。如果是这种情况,那么我建议使用文件元数据来实现这一点。例如:

// Create file metadata including the content type 
StorageMetadata metadata = new StorageMetadata.Builder() 
        .setCustomMetadata("myPDFfile", "localPDFfileName") 
        .build(); 

// Upload the file and metadata 
uploadTask = storageRef.child("pdf/localPDFfileName.pdf").putFile(file, metadata); 

而在您的成功侦听器上,检索文件元数据。如果下载并看起来完整,则从本地电话存储打开PDF。如果没有,那么请尝试从downloadURL下载,就像我在帖子开头提到的那样。这应该涵盖你正在尝试做的验证。

如果我没有正确理解您的问题,请详细说明。我会捡起来并相应地修改我的回复。

+0

“**现在我想打开一个意图来查看这个pdf文件**”我们正在寻找预览PDF文件,而不是下载它。 –

+0

@KarloA.López - 是的,我明白这一点。但是,在不下载内容的情况下,无法预览服务器上的PDF。因此,我建议使用元数据。 –

+0

最后,这是我做的,下载PDF到临时文件并用[PDF viewer](https://github.com/barteksc/AndroidPdfViewer)显示,我正在寻找一个更简单的解决方案,它的一个耻辱' http://drive.google.com/viewerng/viewer?embedded = true&url ='不适用于Firebase PDF文档。 –

相关问题