【问题标题】:How to download the file with original extension from Firebase storage?如何从 Firebase 存储下载具有原始扩展名的文件?
【发布时间】:2017-04-20 20:08:57
【问题描述】:

我正在尝试从 Firebase 存储下载文件。但是当我下载它时,它会给出一些带有.bin 扩展名的文件。但我想得到原始文件名。

这是我的代码。

try {
            URL url = new URL(f_url[0]);
            URLConnection conection = url.openConnection();
            conection.connect();
            int lenghtOfFile = conection.getContentLength();
            InputStream input = new BufferedInputStream(url.openStream(),
                    8192);
            OutputStream output = new FileOutputStream(Environment
                    .getExternalStorageDirectory().toString()
                    +"/Download/"+ URLUtil.guessFileName(f_url[0], null, null));
            Log.i("File name",URLUtil.guessFileName(f_url[0], null, null));
            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                output.write(data, 0, count);
            }
            output.flush();
            output.close();
            input.close();

        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }

f_url 是 firebase 下载网址。谢谢。

【问题讨论】:

  • 您为什么不使用 Firebase SDK?这是文档firebase.google.com/docs/storage/android/download-files
  • 我试过了。首先我创建了 File localFile = File.createTempFile("ayefile","",getExternalFilesDir(null));然后将该文件添加到firebase本地下载功能。但我仍然没有得到扩展。 :(

标签: android firebase firebase-storage


【解决方案1】:

这样做的内置方式实际上非常简单:

StorageReference reference = storage.getReferenceFromUrl("https://firebasestorage.googleapis.com/...");

// Assuming that the file is "name.extension" in Storage
String name = reference.getName().split(".")[0]
String extension = reference.getName().split(".")[1]

File localFile = File.createTempFile(name, extension);

reference.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
        // Local temp file has been created
    }
});

但是如果你不想用简单的方法来做......

让我们简要了解一下您是如何命名文件的:URLUtil.guessFileName(f_url[0], null, null)

根据URLUtil.guessFileName() 文档:“使用 URL 和 contentDisposition 猜测下载将具有的规范文件名。如果未定义文件扩展名,则根据 mimetype 添加文件扩展名。”

我假设您的f_url[0] 是一个没有扩展名的文件,并且由于您没有提供contentDispositionmimetype 作为guessFileName 的参数,因此它不可能知道您想要什么文件扩展名.

您可以从Storage Metadata 获取contentDispositioncontentType(与mimetype 相同),如果您在Storage 中使用扩展名命名您的文件,您应该可以继续使用。

【讨论】:

  • 只是为了澄清,如果文件没有使用扩展名上传怎么办?有没有办法在创建本地 tempFile 之前根据 mime 类型获取扩展名?
  • @AndrewLam 您可以获取元数据、获取内容类型、维护查找表(或可能使用内置 MIME 类型到扩展名的映射),然后下载文件并创建适当的扩展名。
猜你喜欢
  • 2022-01-26
  • 2023-04-01
  • 2012-08-25
  • 2020-06-02
  • 2023-04-08
  • 1970-01-01
  • 2021-03-04
  • 2015-10-14
  • 2021-01-25
相关资源
最近更新 更多