打开存储在Firebase存储中的pdf文件网址

时间:2017-04-06 10:47:24

标签: android pdf firebase firebase-storage

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

以下是我将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");

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

如果有人对此有任何疑问,请帮助我。

非常感谢先进。

7 个答案:

答案 0 :(得分:2)

您应该使用Intent Chooser

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
} 

答案 1 :(得分:1)

请将以下文件/方法添加到您的项目中

  1. PdfDownloader.java
  2. PDFDownloaderAsyncTask.java
  3. 然后使用以下方法 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;
        }
    
    }
    

答案 2 :(得分:1)

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

但是,要解决您的问题,您应该尝试将网址作为网址打开。它将激活手机上的浏览器,进而检测到它需要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下载。这应该涵盖您尝试进行的验证。

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

答案 3 :(得分:0)

如果要在应用程序中打开保存的pdf文件,而不是创建在其他应用程序中打开的意图,则可以使用以下库在Xml文件中创建PdfView。 AndroidPdfViewer(此库还提供了放大功能)

之后,如Firebase Document中所述,使用firebase存储中文件位置的已保存路径引用以字节为单位获取文件,并将其添加为您的PdfView。

例如,您的文件路径将类似于:“ / folder1 / yourfile.pdf”

pdfView = (PDFView) findViewById(R.id.pdfView);
mFirebaseStorage=FirebaseStorage.getInstance().getReference();

final long ONE_MEGABYTE = 1024 * 1024;

mFirebaseStorage.child("YourSavedFilePathRef").getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
    @Override
    public void onSuccess(byte[] bytes) {
 pdfView.fromBytes(bytes).load();
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
        Toast.makeText(MainActivity.this,"download unsuccessful",Toast.LENGTH_LONG).show();
    }
});

答案 4 :(得分:0)

简单代码:)

<body>


  <h1> Welcome to the Ancient game of Lapis, Papyrus, Scalpellus!</h1>

  <div class="c">
    <button id="lbutton"><b>Lapis<b></button>
    <button id="pbutton"><b>Papyrus<b></button>
    <button id="sbutton"><b>Scalpellus<b></button>
  </div>

  <h2> The results are in...</h2>


</body>

希望它能起作用:)

答案 5 :(得分:-1)

尝试对您的Firebase数据库文件URL进行编码。它可以和我一起工作

答案 6 :(得分:-3)

使用Webview查看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);