- Как получить URL из Firebase Storage getDownloadURL
- 10 ответов
- Upload files with Cloud Storage on Android
- Upload Files
- Kotlin+KTX
- Upload from data in memory
- Kotlin+KTX
- Upload from a stream
- Kotlin+KTX
- Upload from a local file
- Kotlin+KTX
- Get a download URL
- Kotlin+KTX
- Add File Metadata
- Kotlin+KTX
- Manage Uploads
- Kotlin+KTX
- Monitor Upload Progress
- Kotlin+KTX
- Handle Activity Lifecycle Changes
- Kotlin+KTX
- Continuing Uploads Across Process Restarts
- Kotlin+KTX
- Kotlin+KTX
- Error Handling
- Full Example
- Kotlin+KTX
- Download files with Cloud Storage on Android
- Create a Reference
- Kotlin+KTX
- Download Files
- Download in memory
- Kotlin+KTX
- Download to a local file
- Kotlin+KTX
- Download Data via URL
- Kotlin+KTX
- Downloading Images with FirebaseUI
- Kotlin+KTX
- Handle Activity Lifecycle Changes
- Kotlin+KTX
- Handle Errors
- Full Example
- Kotlin+KTX
Как получить URL из Firebase Storage getDownloadURL
Я пытаюсь получить «долгосрочную постоянную ссылку для скачивания» для файлов в нашей корзине хранилища Firebase. Я изменил разрешения этого на
И мой код Java выглядит так:
Когда я запускаю это, я получаю ссылку uri, которая выглядит примерно так com.google.android.gms.tasks.zzh@xxx
При попытке получить ссылку выше я изменил последнюю строку перед возвращением, например:
Но при этом я получаю ошибку 403, и приложение вылетает. Консоль сообщает мне, что это пользователь bc не вошел в систему / auth. «Пожалуйста, войдите, прежде чем запрашивать токен»
Вопрос 2. Как это исправить?
10 ответов
Когда вы вызываете getDownloadUrl() , вызов является асинхронным, и вы должны подписаться на успешный обратный вызов, чтобы получить результаты:
Это вернет общедоступный URL-адрес загрузки, который невозможно определить. Если вы только что загрузили файл, этот общедоступный URL будет в обратном вызове успешной загрузки (вам не нужно вызывать другой асинхронный метод после того, как вы загрузили).
Однако, если все, что вам нужно, это String представление ссылки, вы можете просто вызвать .toString()
// Хранилище Firebase — Простота работы с загрузками и загрузками.
здесь я одновременно загружаю и получаю URL изображения .
Что касается меня, я написал свой код на Kotlin, и у меня была такая же ошибка «getDownload ()». Вот и зависимости, которые у меня сработали, и код Kotlin.
implementation ‘com.google.firebase:firebase-storage:18.1.0’ зависимости хранилища firebase
Это то, что я добавил, и это сработало для меня в Котлине. Storage () будет предшествовать Download ()
Метод getDownloadUrl устарел в новом обновлении firebase. Вместо этого используйте следующий метод. taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()
Измените полученный URI на URL
Вы можете загрузить изображения в firestore и получить URL-адрес загрузки, как показано ниже:
Метод getDownloadUrl был удален в версиях firebase выше 11.0.5. Я рекомендую использовать версию 11.0.2, в которой все еще используется этот метод.
Источник
Upload files with Cloud Storage on Android
Cloud Storage for Firebase allows you to quickly and easily upload files to a Cloud Storage bucket provided and managed by Firebase.
Note: By default, a Cloud Storage bucket requires Firebase Authentication to perform any action on the bucket’s data or files. You can change your Firebase Security Rules for Cloud Storage to allow unauthenticated access. Since Firebase and your project’s default App Engine app share this bucket, configuring public access may make newly uploaded App Engine files publicly accessible, as well. Be sure to restrict access to your Cloud Storage bucket again when you set up Authentication.
Upload Files
To upload a file to Cloud Storage, you first create a reference to the full path of the file, including the file name.
Kotlin+KTX
Once you’ve created an appropriate reference, you then call the putBytes() , putFile() , or putStream() method to upload the file to Cloud Storage.
You cannot upload data with a reference to the root of your Cloud Storage bucket. Your reference must point to a child URL.
Upload from data in memory
The putBytes() method is the simplest way to upload a file to Cloud Storage. putBytes() takes a byte[] and returns an UploadTask that you can use to manage and monitor the status of the upload.
Kotlin+KTX
Because putBytes() accepts a byte[] , it requires your app to hold the entire contents of a file in memory at once. Consider using putStream() or putFile() to use less memory.
Upload from a stream
The putStream() method is the most versatile way to upload a file to Cloud Storage. putStream() takes an InputStream and returns an UploadTask that you can use to manage and monitor the status of the upload.
Kotlin+KTX
Upload from a local file
You can upload local files on the device, such as photos and videos from the camera, with the putFile() method. putFile() takes a File and returns an UploadTask which you can use to manage and monitor the status of the upload.
Kotlin+KTX
Get a download URL
After uploading a file, you can get a URL to download the file by calling the getDownloadUrl() method on the StorageReference :
Kotlin+KTX
Add File Metadata
You can also include metadata when you upload files. This metadata contains typical file metadata properties such as name , size , and contentType (commonly referred to as MIME type). The putFile() method automatically infers the MIME type from the File extension, but you can override the auto-detected type by specifying contentType in the metadata. If you do not provide a contentType and Cloud Storage cannot infer a default from the file extension, Cloud Storage uses application/octet-stream . See the Use File Metadata section for more information about file metadata.
Kotlin+KTX
Manage Uploads
In addition to starting uploads, you can pause, resume, and cancel uploads using the pause() , resume() , and cancel() methods. Pause and resume events raise pause and progress state changes respectively. Canceling an upload causes the upload to fail with an error indicating that the upload was canceled.
Kotlin+KTX
Monitor Upload Progress
You can add listeners to handle success, failure, progress, or pauses in your upload task:
Listener Type | Typical Usage |
---|---|
OnProgressListener | This listener is called periodically as data is transferred and can be used to populate an upload/download indicator. |
OnPausedListener | This listener is called any time the task is paused. |
OnSuccessListener | This listener is called when the task has successfully completed. |
OnFailureListener | This listener is called any time the upload has failed. This can happen due to network timeouts, authorization failures, or if you cancel the task. |
OnFailureListener is called with an Exception instance. Other listeners are called with an UploadTask.TaskSnapshot object. This object is an immutable view of the task at the time the event occurred. An UploadTask.TaskSnapshot contains the following properties:
Property | Type | Description |
---|---|---|
getDownloadUrl | String | A URL that can be used to download the object. This is a public unguessable URL that can be shared with other clients. This value is populated once an upload is complete. |
getError | Exception | If the task failed, this will have the cause as an Exception. |
getBytesTransferred | long | The total number of bytes that have been transferred when this snapshot was taken. |
getTotalByteCount | long | The total number of bytes expected to be uploaded. |
getUploadSessionUri | String | A URI that can be used to continue this task via another call to putFile. |
getMetadata | StorageMetadata | Before an upload completes, this is the metadata being sent to the server. After the upload completes, this is the metadata returned by the server. |
getTask | UploadTask | The task that created this snapshot. Use this task to cancel, pause, or resume the upload. |
getStorage | StorageReference | The StorageReference used to create the UploadTask . |
The UploadTask event listeners provide a simple and powerful way to monitor upload events.
Kotlin+KTX
Handle Activity Lifecycle Changes
Uploads continue in the background even after activity lifecycle changes (such as presenting a dialog or rotating the screen). Any listeners you had attached will also remain attached. This could cause unexpected results if they get called after the activity is stopped.
You can solve this problem by subscribing your listeners with an activity scope to automatically unregister them when the activity stops. Then, use the getActiveUploadTasks method when the activity restarts to obtain upload tasks that are still running or recently completed.
The example below demonstrates this and also shows how to persist the storage reference path used.
Kotlin+KTX
getActiveUploadTasks retrieves all active upload tasks at and below the provided reference, so you may need to handle multiple tasks.
Continuing Uploads Across Process Restarts
If your process is shut down, any uploads in progress will be interrupted. However, you can continue uploading once the process restarts by resuming the upload session with the server. This can save time and bandwidth by not starting the upload from the start of the file.
To do this, begin uploading via putFile . On the resulting StorageTask , call getUploadSessionUri and save the resulting value in persistent storage (such as SharedPreferences).
Kotlin+KTX
After your process restarts with an interrupted upload, call putFile again. But this time also pass the Uri that was saved.
Kotlin+KTX
Sessions last one week. If you attempt to resume a session after it has expired or if it had experienced an error, you will receive a failure callback. It is your responsibility to ensure the file has not changed between uploads.
Error Handling
There are a number of reasons why errors may occur on upload, including the local file not existing, or the user not having permission to upload the desired file. You can find more information about errors in the Handle Errors section of the docs.
Full Example
A full example of an upload with progress monitoring and error handling is shown below:
Kotlin+KTX
Now that you’ve uploaded files, let’s learn how to download them from Cloud Storage.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Источник
Download files with Cloud Storage on Android
Cloud Storage for Firebase allows you to quickly and easily download files from a Cloud Storage bucket provided and managed by Firebase.
Note: By default, a Cloud Storage bucket requires Firebase Authentication to perform any action on the bucket’s data or files. You can change your Firebase Security Rules for Cloud Storage to allow unauthenticated access. Since Firebase and your project’s default App Engine app share this bucket, configuring public access may make newly uploaded App Engine files publicly accessible, as well. Be sure to restrict access to your Cloud Storage bucket again when you set up Authentication.
Create a Reference
To download a file, first create a Cloud Storage reference to the file you want to download.
You can create a reference by appending child paths to the root of your Cloud Storage bucket, or you can create a reference from an existing gs:// or https:// URL referencing an object in Cloud Storage.
Kotlin+KTX
Download Files
Once you have a reference, you can download files from Cloud Storage by calling the getBytes() or getStream() . If you prefer to download the file with another library, you can get a download URL with getDownloadUrl() .
Download in memory
Download the file to a byte[] with the getBytes() method. This is the easiest way to download a file, but it must load the entire contents of your file into memory. If you request a file larger than your app’s available memory, your app will crash. To protect against memory issues, getBytes() takes a maximum amount of bytes to download. Set the maximum size to something you know your app can handle, or use another download method.
Kotlin+KTX
Download to a local file
The getFile() method downloads a file directly to a local device. Use this if your users want to have access to the file while offline or to share the file in a different app. getFile() returns a DownloadTask which you can use to manage your download and monitor the status of the download.
Kotlin+KTX
If you want to actively manage your download, see Manage Downloads for more information.
Download Data via URL
If you already have download infrastructure based around URLs, or just want a URL to share, you can get the download URL for a file by calling the getDownloadUrl() method on a Cloud Storage reference.
Kotlin+KTX
Downloading Images with FirebaseUI
FirebaseUI provides simple, customizable, and production-ready native mobile bindings to eliminate boilerplate code and promote Google best practices. Using FirebaseUI you can quickly and easily download, cache, and display images from Cloud Storage using our integration with Glide.
First, add FirebaseUI to your app/build.gradle :
Then you can load images directly from Cloud Storage into an ImageView :
Kotlin+KTX
Handle Activity Lifecycle Changes
Downloads continue in the background even after activity lifecycle changes (such as presenting a dialog or rotating the screen). Any listeners you had attached will also remain attached. This could cause unexpected results if they get called after the activity is stopped.
You can solve this problem by subscribing your listeners with an activity scope to automatically unregister them when the activity stops. Then, use the getActiveDownloadTasks method when the activity restarts to obtain download tasks that are still running or recently completed.
The example below demonstrates this and also shows how to persist the storage reference path used.
Kotlin+KTX
Handle Errors
There are a number of reasons why errors may occur on download, including the file not existing, or the user not having permission to access the desired file. More information on errors can be found in the Handle Errors section of the docs.
Full Example
A full example of a download with error handling is shown below:
Kotlin+KTX
You can also get and update metadata for files that are stored in Cloud Storage.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Источник