[Firebase] 03 - Cloud Storage: object storage service
根据db上的聊天信息控制大文件的下载。
Everything is based on Chatting System.
-
通过db存放少量图片
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK) { if (data == null) { Toast.makeText(context, "Warn: data == null", Toast.LENGTH_LONG).show(); return; } try { InputStream inputStream = context.getContentResolver().openInputStream(data.getData());
////////////////////////////////////////////////////////////////////////////////////////////// // getContext().getContentResolver()返回的是ContentResolver对象:负责获取ContentProvider提供的数据
// 通过 ContentResolver 来读取其他应用的信息,最常用的莫过于读取联系人, 多媒体信息等!
// Ref: [Android] 02 - Four Basic Components and Intent
//////////////////////////////////////////////////////////////////////////////////////////////
Bitmap imgBitmap = BitmapFactory.decodeStream(inputStream); imgBitmap = ImageUtils.cropToSquare(imgBitmap);
// 自定义 InputStream is = ImageUtils.convertBitmapToInputStream(imgBitmap); final Bitmap liteImage = ImageUtils.makeImageLite(is, imgBitmap.getWidth(), imgBitmap.getHeight(), ImageUtils.AVATAR_WIDTH, ImageUtils.AVATAR_HEIGHT);
// 加密 String imageBase64 = ImageUtils.encodeBase64(liteImage); myAccount.avata = imageBase64; waitingDialog.setCancelable(false) .setTitle("Avatar updating....") .setTopColorRes(R.color.colorPrimary) .show();
userDB.child("avata").setValue(imageBase64) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()){ waitingDialog.dismiss(); SharedPreferenceHelper preferenceHelper = SharedPreferenceHelper.getInstance(context); preferenceHelper.saveUserInfo(myAccount); avatar.setImageDrawable(ImageUtils.roundedImage(context, liteImage)); new LovelyInfoDialog(context) .setTopColorRes(R.color.colorPrimary) .setTitle("Success") .setMessage("Update avatar successfully!") .show(); } } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { waitingDialog.dismiss(); Log.d("Update Avatar", "failed"); new LovelyInfoDialog(context) .setTopColorRes(R.color.colorAccent) .setTitle("False") .setMessage("False to update avatar") .show(); } }); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
-
通过storage存放大量图片
不同的用户,分配一个单独的文件夹,存放图片,音频什么的各种类型的资源。

1. Firebase : Differences between realtime database and file storage
2. Protocal design.

三类聊天信息:
| CHAT | TEXT | text | comment |
| CHAT | VOICE | url | comment |
| CHAT | IMAGE | url | comment |
private void checkFilePermissions() {
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){ int permissionCheck = UploadActivity.this.checkSelfPermission("Manifest.permission.READ_EXTERNAL_STORAGE"); permissionCheck += UploadActivity.this.checkSelfPermission("Manifest.permission.WRITE_EXTERNAL_STORAGE"); if (permissionCheck != 0) { this.requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE,android.Manifest.permission.READ_EXTERNAL_STORAGE}, 1001); //Any number } }else{ Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version < LOLLIPOP."); } }
private void addFilePaths(){
Log.d(TAG, "addFilePaths: Adding file paths."); String path = System.getenv("EXTERNAL_STORAGE"); Log.d(TAG, "SD: " + path); // "/sdcard"
pathArray.add(path+"/image1.jpg"); pathArray.add(path+"/image2.jpg"); pathArray.add(path+"/image3.jpg"); loadImageFromStorage(); // ----> }
将图片拖入sdcard文件夹中。

private void loadImageFromStorage() { try{ String path = pathArray.get(array_position); File f=new File(path, ""); Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f)); image.setImageBitmap(b);
}catch (FileNotFoundException e){ Log.e(TAG, "loadImageFromStorage: FileNotFoundException: " + e.getMessage() ); } }
图片准备就绪,上传到storage相应的文件夹。

上传
设置上传按钮,以及对应的响应事件。
btnUpload.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) { Log.d(TAG, "onClick: Uploading Image."); mProgressDialog.setMessage("Uploading Image..."); mProgressDialog.show();
//get the signed in user FirebaseUser user = auth.getCurrentUser(); String userID = user.getUid(); String name = imageName.getText().toString(); if(!name.equals("")){ Uri uri = Uri.fromFile(new File(pathArray.get(array_position)));
// ref:android之Uri的常用几个例子
StorageReference storageReference = mStorageRef.child("images/users/" + userID + "/" + name + ".jpg"); // <---- storageReference.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { // Get a URL to the uploaded content Uri downloadUrl = taskSnapshot.getDownloadUrl(); toastMessage("Upload Success"); mProgressDialog.dismiss(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { toastMessage("Upload Failed"); mProgressDialog.dismiss(); } }) ; } } });
下载
from: how can I download image on firebase storage?
StorageReference storageRef = storage.getReference(); storageRef.child("images/stars.jpg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { // Got the download URL for 'users/me/profile.png' } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { // Handle any errors } });



浙公网安备 33010602011771号