// Create a storage reference from our app
StorageReference storageRef = storage.getReference();
// Or Create a reference to a file from a Google Cloud Storage URI
StorageReference gsReference =
storage.getReferenceFromUrl("gs://bucket/images/stars.jpg");
/*In this case we'll use this kind of reference*/
//Download file in Memory
StorageReference islandRef = storageRef.child("images/island.jpg");
final long ONE_MEGABYTE = 1024 * 1024;
islandRef.getBytes(ONE_MEGABYTE).addOnSuccessListener(new
OnSuccessListener<byte[]>() {
@Override
public void onSuccess(byte[] bytes) {
// Data for "images/island.jpg" is returns, use this as needed
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle any errors
}
});
我回答这个问题有点晚了。我也遇到了同样的问题,但是获取文件的URL(例如:在Firebase文档中 getDownloadUrl()中显示)并不能解决下载文件的整个问题。
这是因为向浏览器发送下载(或附件)响应需要文件内容(而不是URL)。为了获取URL并获取实际文件内容,需要进行HTTP请求,但对于使用免费Spark Firebase帐户的我们来说,这不是一个选项。
为了解决这个问题,我使用了存储桶中的download()
方法,它允许我将存储文件保存为本地tmp文件。然后,我使用fs读取流将文件内容传输到云函数响应中...
const fireapp = '<thebucket>.appspot.com';
const gcs = require('@google-cloud/storage')({keyFilename:'serviceAccount.json'});
const bucket = gcs.bucket(fireapp);
// storage path
let fn = 'folder/theimage.png';
// allow CORS
res.set('Access-Control-Allow-Origin', '*');
// download w/o external http request
// by download file from bucket
// and saving to tmp folder
const tempFilePath = path.join(os.tmpdir(), "tmpfile.jpg");
bucket.file(fn).download({destination: tempFilePath}).then(()=>{
console.log('Image downloaded locally to', tempFilePath);
var filestream = fs.createReadStream(tempFilePath);
filestream.pipe(response);
});
试试这个
// Create a storage reference from our app
StorageReference storageRef = storage.getReferenceFromUrl("gs://<your-bucket-name>");
// Create a reference with an initial file path and name
StorageReference pathReference = storageRef.child("users/me/yourpics.png");
storageRef.child("users/me/yourpics.png").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
}
});
Download-files
https://firebase.google.com/docs/storage/android/download-files
要下载文件,首先需要创建一个指向要下载的文件的云存储引用。
您可以通过将子路径附加到存储根来创建引用,也可以从现有的指向云存储中对象的gs://
或https:// URL
创建引用。
// Create a storage reference from our app
StorageReference storageRef = storage.getReference();
// Create a reference with an initial file path and name
StorageReference pathReference = storageRef.child("images/stars.jpg");
images
是根目录的子目录。
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
}
});
package com.example.package.myfirestore;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.FirebaseFirestore;
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.io.IOException;
import java.net.URI;
/**
* Created by Yeshveer on 6/9/2018.
*/
public class UploadImg extends AppCompatActivity{
private TextView textView1;
private ImageView img1;
private EditText edittext1;
private Button Btn1;
private Button Btn2;
int Image_requestcode=7;
ProgressDialog pd;
Uri filpath;
FirebaseStorage storage1;
StorageReference storageReference;
StorageReference storageReference2;
FirebaseFirestore db;
FirebaseStorage storage;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = (TextView) findViewById(R.id.textView1);
img1 = (ImageView) findViewById(R.id.img1);
edittext1 = (EditText) findViewById(R.id.edittext1);
Btn1 = (Button) findViewById(R.id.Btn1);
Btn2 = (Button) findViewById(R.id.Btn2);
// Create Storage Referece
storage1=FirebaseStorage.getInstance();
storageReference = storage1.getReference();
//PD details
pd=new ProgressDialog(this);
pd.setTitle("Uploading Image");
// Image Chooser
Btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Creating Intent
Intent intent = new Intent();
//Setting Intent of Image type and select Image from Mobile Storage
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Please Select Image"), Image_requestcode);
}
});
Btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
UploadingStart();
}
});
}
private void UploadingStart() {
// Image path Print
textView1.setText(GetFileExtension(filpath));
pd.show();
storageReference2=storageReference.child("images/"+"hello"+"."+GetFileExtension(filpath));
storageReference2.putFile(filpath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
pd.dismiss();
Toast.makeText(UploadImg.this, "Uploaded Successfully", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
pd.dismiss();
Toast.makeText(UploadImg.this, "Error in Uploading, Please check Internet connection", Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress=(100.0* taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
pd.setMessage("Progress is "+(int)progress+"%");
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==Image_requestcode && resultCode==RESULT_OK && data != null && data.getData() != null){
filpath=data.getData();
try {
// Image content resolver
Bitmap bitmap= MediaStore.Images.Media.getBitmap(getContentResolver(),filpath);
img1.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Method for file etention and path
public String GetFileExtension(Uri uri){
ContentResolver contentResolver=getContentResolver();
MimeTypeMap mimeTypeMap=MimeTypeMap.getSingleton();
// Return file Extension
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
}
}
尝试一下:kotlin
val storageFirebase = Firebase.storage
val fullUrl = "gs://[bucket name]/[Folder]/[FileName]" or
"gs://[bucket name]/[FileName]"
// Create a reference to a file from a Google Cloud Storage URI
storageFirebase.getReferenceFromUrl(fullUrl).downloadUrl
.addOnSuccessListener { urlImage ->
{ Glide.with(context).load(urlImage).into(imageView) }
.addOnFailureListener { Toast.makeText(context, it.message, Toast.LENGTH_SHORT).show() }
参考资料:https://firebase.google.com/docs/storage/android/download-files