如何使用 Android Studio 在 Firebase 数据库中上传视频?
Firebase是一个移动和 Web 应用程序开发平台。它提供 Web 应用程序或移动应用程序可能需要的服务。 Firebase 为 Firebase 应用程序提供安全的文件上传和下载。本文介绍了如何构建一个能够从移动图库中选择视频并将视频上传到 Firebase 存储的 Android 应用程序。
分步实施
第 1 步:创建一个新项目
要在 Android Studio 中创建新项目,请参阅如何在 Android Studio 中创建/启动新项目。请注意,选择Java作为编程语言。或者打开一个您想要添加身份验证的现有项目并将 firebase 添加到该 android 应用程序。
步骤 2. 在 build.gradle (Module:app) 文件中添加这些依赖项
implementation 'com.google.firebase:firebase-storage:19.1.0'
implementation 'com.google.firebase:firebase-database:20.0.0'
第 3 步:使用 activity_main.xml 文件
导航到app > res > layout > activity_main.xml并将以下代码添加到该文件。下面是activity_main.xml文件的代码。
XML
Java
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
Button uploadv;
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialise layout
uploadv = findViewById(R.id.uploadv);
uploadv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Code for showing progressDialog while uploading
progressDialog = new ProgressDialog(MainActivity.this);
choosevideo();
}
});
}
// choose a video from phone storage
private void choosevideo() {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 5);
}
Uri videouri;
// startActivityForResult is used to receive the result, which is the selected video.
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 5 && resultCode == RESULT_OK && data != null && data.getData() != null) {
videouri = data.getData();
progressDialog.setTitle("Uploading...");
progressDialog.show();
uploadvideo();
}
}
private String getfiletype(Uri videouri) {
ContentResolver r = getContentResolver();
// get the file type ,in this case its mp4
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(r.getType(videouri));
}
private void uploadvideo() {
if (videouri != null) {
// save the selected video in Firebase storage
final StorageReference reference = FirebaseStorage.getInstance().getReference("Files/" + System.currentTimeMillis() + "." + getfiletype(videouri));
reference.putFile(videouri).addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful()) ;
// get the link of video
String downloadUri = uriTask.getResult().toString();
DatabaseReference reference1 = FirebaseDatabase.getInstance().getReference("Video");
HashMap map = new HashMap<>();
map.put("videolink", downloadUri);
reference1.child("" + System.currentTimeMillis()).setValue(map);
// Video uploaded successfully
// Dismiss dialog
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Video Uploaded!!", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// Error, Image not uploaded
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Failed " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener() {
// Progress Listener for loading
// percentage on the dialog box
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
// show the progress bar
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded " + (int) progress + "%");
}
});
}
}
}
第 4 步:使用MainActivity。Java
转到MainActivity。 Java文件并参考以下代码。下面是MainActivity 的代码。 Java文件。代码中添加了注释以更详细地理解代码。
Java
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
Button uploadv;
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialise layout
uploadv = findViewById(R.id.uploadv);
uploadv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Code for showing progressDialog while uploading
progressDialog = new ProgressDialog(MainActivity.this);
choosevideo();
}
});
}
// choose a video from phone storage
private void choosevideo() {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 5);
}
Uri videouri;
// startActivityForResult is used to receive the result, which is the selected video.
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 5 && resultCode == RESULT_OK && data != null && data.getData() != null) {
videouri = data.getData();
progressDialog.setTitle("Uploading...");
progressDialog.show();
uploadvideo();
}
}
private String getfiletype(Uri videouri) {
ContentResolver r = getContentResolver();
// get the file type ,in this case its mp4
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(r.getType(videouri));
}
private void uploadvideo() {
if (videouri != null) {
// save the selected video in Firebase storage
final StorageReference reference = FirebaseStorage.getInstance().getReference("Files/" + System.currentTimeMillis() + "." + getfiletype(videouri));
reference.putFile(videouri).addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful()) ;
// get the link of video
String downloadUri = uriTask.getResult().toString();
DatabaseReference reference1 = FirebaseDatabase.getInstance().getReference("Video");
HashMap map = new HashMap<>();
map.put("videolink", downloadUri);
reference1.child("" + System.currentTimeMillis()).setValue(map);
// Video uploaded successfully
// Dismiss dialog
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Video Uploaded!!", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// Error, Image not uploaded
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Failed " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener() {
// Progress Listener for loading
// percentage on the dialog box
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
// show the progress bar
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded " + (int) progress + "%");
}
});
}
}
}
输出:
Firebase 存储映像:
实时数据库: