In this tutorial you will learn to upload image to firebase storage in android.
在本教程中,您将学习将图像上传到Android中的Firebase存储。
Firebase storage provides facility to upload any file like image, video, audio, etc without using server side code.
Firebase存储提供了无需使用服务器端代码即可上传图像,视频,音频等任何文件的功能。
Lets quickly learn how we can implement this in android.
让我们快速学习如何在android中实现这一点。
Also Read: Android Push Notification Using Firebase Cloud Messaging (FCM)
另请参阅: 使用Firebase Cloud Messaging(FCM)的Android推送通知
Android将图像上传到Firebase存储 (Android Upload Image to Firebase Storage)
将Firebase添加到项目 (Adding Firebase to Project)
First of all we have to connect our project to firebase and then add the required dependencies. For doing this just follow below steps.
首先,我们必须将项目连接到Firebase,然后添加所需的依赖项。 为此,请按照以下步骤操作。
Note: Below method of adding firebase will work only in android studio 2.2 and higher versions. If you are using any older version then follow this link to learn how to add firebase.
注意:以下添加Firebase的方法仅在android studio 2.2及更高版本中有效。 如果您使用的是旧版本,请点击此链接以了解如何添加Firebase。
1. In android studio go to Tools > Firebase. It will open firebase assistant that allows us to add firebase to android studio within few clicks.
1.在android studio中,转到工具> Firebase 。 它将打开firebase助手,使我们可以在几下单击中将firebase添加到android studio。
![Android Upload Image to Firebase Storage Tutorial 1](https://i-blog.csdnimg.cn/blog_migrate/1900070140c88960e68dd5d7ac9beb4e.png)
2. Now you will see a window as shown below. Just click on Storage section and then click Upload and download a file with Firebase Storage.
2.现在,您将看到如下所示的窗口。 只需单击“ 存储”部分,然后单击“ 上传并使用Firebase Storage下载文件” 。
![Android Upload Image to Firebase Storage Tutorial 2](https://i-blog.csdnimg.cn/blog_migrate/09808188a387d293305851df4fefe99c.png)
3. Click on Connect to Firebase, this will open a browser where you have to login to firebase using google account.
3.单击“ 连接到Firebase” ,这将打开一个浏览器,您必须在其中使用Google帐户登录到Firebase 。
![Android Upload Image to Firebase Storage Tutorial 3](https://i-blog.csdnimg.cn/blog_migrate/f00148c895ec4bd27f59a359a8576107.png)
4. After that you will see a window as shown below. Here you can create a new firebase project or use an existing one. In my case I am using an existing project. Finally click on Connect to Firebase.
4.之后,您将看到如下所示的窗口。 在这里您可以创建一个新的firebase项目或使用现有的项目。 就我而言,我正在使用现有项目。 最后单击“ 连接到Firebase” 。
![Android Upload Image to Firebase Storage Tutorial 4](https://i-blog.csdnimg.cn/blog_migrate/2c32dff14ed63daf1c962537e26ca3cf.png)
5. Now click on Add Firebase Storage to your app. In the next window click on Accept Changes to add all firebase storage related dependencies to android studio project.
5.现在,单击“ 将 Firebase存储 添加 到您的应用程序” 。 在下一个窗口中,单击“ 接受更改” ,将所有与Firebase存储相关的依赖项添加到android studio项目中。
![Android Upload Image to Firebase Storage Tutorial 3](https://i-blog.csdnimg.cn/blog_migrate/f00148c895ec4bd27f59a359a8576107.png)
![Android Upload Image to Firebase Storage Tutorial 5](https://i-blog.csdnimg.cn/blog_migrate/0207e570db48d5734941ff981cf08900.png)
变更规则 (Change Rules)
By default we are not allowed to access firebase storage without authentication. To change it go to firebase console using any web browser. Open the firebase project that you have used in above steps and go to Storage and then Rules tab. Now change read and write rules to true as shown in below image.
默认情况下,未经身份验证,不允许我们访问Firebase存储。 要进行更改,请使用任何网络浏览器进入Firebase控制台。 打开您在上述步骤中使用过的firebase项目,然后依次转到“ 存储”和“规则”选项卡。 现在,将读取和写入规则更改为true,如下图所示。
![Android Upload Image to Firebase Storage Tutorial 6](https://i-blog.csdnimg.cn/blog_migrate/bcf00b1793e5d8b6980cbd14c9d56fb8.png)
Android专案 (Android Project)
Now comes the actual coding part. In this simple example I have given two button, one to choose the image from gallery and another to upload it.
现在是实际的编码部分。 在这个简单的示例中,我给出了两个按钮,一个用于从图库中选择图像,另一个用于上载图像。
1. Firstly image is selected from gallery using file chooser and displayed in ImageView.
1.首先使用文件选择器从图库中选择图像并显示在ImageView中。
2. Before using firebase we have to get its instance and then using the instance create reference to firebase storage app. It can be done by following code.
2.在使用firebase之前,我们必须获取其实例,然后使用该实例创建对firebase存储应用程序的引用。 可以通过以下代码完成。
//creating reference to firebase storage
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://fir-example-c4312.appspot.com"); //change the url according to your firebase app
3. Now a child reference is created and using it we call putFile() method to upload image to firebase storage.
3.现在创建了一个子引用,并使用它调用putFile()方法将图像上传到Firebase存储。
4. If image is uploaded successfully then success message is shown otherwise error is shown in toast.
4.如果图像成功上传,则会显示成功消息,否则将在烤面包中显示错误。
Below I have shared the full code for this.
下面,我分享了完整的代码。
完整的源代码 (Full Source Code)
activity_main.xml
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.firebaseimageupload.MainActivity"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Choose Image"
android:id="@+id/chooseImg"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Upload Image"
android:id="@+id/uploadImg"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="300dp"
android:id="@+id/imgView"/>
</LinearLayout>
MainActivity.java
MainActivity.java
package com.firebaseimageupload;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
public class MainActivity extends AppCompatActivity {
Button chooseImg, uploadImg;
ImageView imgView;
int PICK_IMAGE_REQUEST = 111;
Uri filePath;
ProgressDialog pd;
//creating reference to firebase storage
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://fir-example-c4312.appspot.com"); //change the url according to your firebase app
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chooseImg = (Button)findViewById(R.id.chooseImg);
uploadImg = (Button)findViewById(R.id.uploadImg);
imgView = (ImageView)findViewById(R.id.imgView);
pd = new ProgressDialog(this);
pd.setMessage("Uploading....");
chooseImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
}
});
uploadImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(filePath != null) {
pd.show();
StorageReference childRef = storageRef.child("image.jpg");
//uploading the image
UploadTask uploadTask = childRef.putFile(filePath);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
pd.dismiss();
Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
pd.dismiss();
Toast.makeText(MainActivity.this, "Upload Failed -> " + e, Toast.LENGTH_SHORT).show();
}
});
}
else {
Toast.makeText(MainActivity.this, "Select an image", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
//getting image from gallery
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting image to ImageView
imgView.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Now run and test your app.
现在运行并测试您的应用程序。
Screenshots
屏幕截图
![Android Upload Image to Firebase Storage Tutorial](https://i-blog.csdnimg.cn/blog_migrate/ef0f3a89fbd534603264505795eb1e3a.png)
When you will login to firebase console the uploaded image will be shown something as given below.
当您登录到Firebase控制台时,将显示上传的图像,如下所示。
![Android Upload Image to Firebase Storage Tutorial 7](https://i-blog.csdnimg.cn/blog_migrate/478ef31e302298972e512453b4ec198e.png)
Comment below if you have any queries related to above android upload image to firebase storage example.
如果您有任何与上述android上载图像到Firebase存储示例相关的查询,请在下面评论。
翻译自: https://www.thecrazyprogrammer.com/2017/02/android-upload-image-firebase-storage-tutorial.html