我使用firebase构建了一个聊天应用程序,我想将多个图像发送到firebase存储。
使用此库
compile' com.github.darsh2:MultipleImageSelect:3474549'
在顶部
preferred_district1
onCreate()方法
private StorageReference storageRef;
private FirebaseApp app;
private FirebaseStorage storage;
按钮点击操作
app = FirebaseApp.getInstance();
storage =FirebaseStorage.getInstance(app);
活动结果
Gallary.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(ChatActivity.this, AlbumSelectActivity.class);
intent.putExtra(Constants.INTENT_EXTRA_LIMIT, 10);
startActivityForResult(intent, Constants.REQUEST_CODE);
pwindo1.dismiss();
}
});
答案 0 :(得分:4)
工作正常。
if (requestCode == Constants.REQUEST_CODE && resultCode == RESULT_OK) {
ArrayList<Image> images = data.getParcelableArrayListExtra(Constants.INTENT_EXTRA_IMAGES);
Uri[] uri=new Uri[images.size()];
for (int i =0 ; i < images.size(); i++) {
uri[i] = Uri.parse("file://"+images.get(i).path);
storageRef = storage.getReference("photos");
final StorageReference ref = storageRef.child(uri[i].getLastPathSegment());
ref.putFile(uri[i])
.addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
String content = downloadUrl.toString();
if (content.length() > 0) {
editWriteMessage.setText("");
Message newMessage = new Message();
newMessage.text = content;
newMessage.idSender = StaticConfig.UID;
newMessage.idReceiver = roomId;
newMessage.timestamp = System.currentTimeMillis();
FirebaseDatabase.getInstance().getReference().child("message/" + roomId).push().setValue(newMessage);
}
}
});
}
}
答案 1 :(得分:1)
变量
onCreate()
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uploaderBtn = findViewById(R.id.uploader);
chooserBtn = findViewById(R.id.chooser);
alert = findViewById(R.id.alert);
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Uploading Images please Wait.........!!!!!!");
chooserBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(intent, PICK_IMAGE);
}
});
上载按钮
uploaderBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
urlStrings = new ArrayList<>();
progressDialog.show();
alert.setText("If Loading Takes to long press button again");
StorageReference ImageFolder = FirebaseStorage.getInstance().getReference().child("ImageFolder");
for (upload_count = 0; upload_count < ImageList.size(); upload_count++) {
Uri IndividualImage = ImageList.get(upload_count);
final StorageReference ImageName = ImageFolder.child("Images" + IndividualImage.getLastPathSegment());
ImageName.putFile(IndividualImage).addOnSuccessListener(
new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
ImageName.getDownloadUrl().addOnSuccessListener(
new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
urlStrings.add(String.valueOf(uri));
if (urlStrings.size() == ImageList.size()){
storeLink(urlStrings);
}
}
}
);
}
}
);
}
}
});
}
if (urlStrings.size() == ImageList.size()){
storeLink(urlStrings);
}
存储到Firebase实时数据库的链接
private void storeLink(ArrayList<String> urlStrings) {
HashMap<String, String> hashMap = new HashMap<>();
for (int i = 0; i <urlStrings.size() ; i++) {
hashMap.put("ImgLink"+i, urlStrings.get(i));
}
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("User");
databaseReference.push().setValue(hashMap)
.addOnCompleteListener(
new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Successfully Uplosded", Toast.LENGTH_SHORT).show();
}
}
}
).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(MainActivity.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
progressDialog.dismiss();
alert.setText("Uploaded Successfully");
uploaderBtn.setVisibility(View.GONE);
ImageList.clear();
}
onActivityResult()
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE) {
if (resultCode == RESULT_OK) {
if (data.getClipData() != null) {
int countClipData = data.getClipData().getItemCount();
int currentImageSlect = 0;
while (currentImageSlect < countClipData) {
ImageUri = data.getClipData().getItemAt(currentImageSlect).getUri();
ImageList.add(ImageUri);
currentImageSlect = currentImageSlect + 1;
}
alert.setVisibility(View.VISIBLE);
alert.setText("You have selected" + ImageList.size() + "Images");
chooserBtn.setVisibility(View.GONE);
} else {
Toast.makeText(this, "Please Select Multiple Images", Toast.LENGTH_SHORT).show();
}
}
}
}
}
答案 2 :(得分:0)
我创建了这个实用程序类,以便在协程的帮助下使用kotlin将多个图像上传到Firebase存储。如果您有任何改进,请告诉我。
您需要首先添加这些依赖项。
实现'com.google.firebase:firebase-storage-ktx:19.1.1'
// Firebase通过kotlinx-coroutines-play-services库为Coroutines添加了支持
实现“ org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.3.1”
有关更多信息,请检查link,github link
object FirebaseUtils {
suspend fun uploadPhotos(photosUri: ArrayList<File>): List<PhotoUrl> {
val storageRef = Firebase.storage.reference
val photosUrls = ArrayList<PhotoUrl>()
val uploadedPhotosUriLink = withContext(CoroutineScope(Dispatchers.IO).coroutineContext) {
(photosUri.indices).map { index ->
async(Dispatchers.IO) {
uploadPhoto(storageRef, photosUri[index])
}
}
}.awaitAll()
uploadedPhotosUriLink.forEach { photoUriLink -> photosUrls.add(PhotoUrl(photoUriLink.toString())) }
return photosUrls
}
private suspend fun uploadPhoto(storageRef: StorageReference, photoFile: File): Uri {
val fileName = UUID.randomUUID().toString()
val fileUri = Uri.fromFile(photoFile)
return storageRef.child(fileName)
.putFile(fileUri)
.await()
.storage
.downloadUrl
.await()
}
}
答案 3 :(得分:0)
对于从库中选择的图像具有相同顺序的返回列表图像网址 不要在每个uri都使用for循环
在获得ArrayList<Uri> imageUriList
之后,现在要将其上传到Firebase存储,然后以您选择的相同顺序返回每个图像的URL列表,因此我在以下方法上使用递归直到上传所有uri
private void uploadImages(@NonNull ArrayList<String> imagesUrl,ArrayList<Uri> imageUriList) {
StorageReference storageReference = FirebaseStorage.getInstance().getReference("Products").child(UUID.randomUUID().toString());
Uri uri = imageUriList.get(imagesUrl.size());
storageReference
.putFile(uri).addOnSuccessListener(taskSnapshot ->
storageReference.getDownloadUrl().addOnCompleteListener(task -> {
String url = Objects.requireNonNull(task.getResult()).toString();
imagesUrl.add(url);
//if same size so all image is uploaded, then sent list of url to to some method
if(imagesUrl .size() == imageUriList.size()){
allImageUploadedNow(imagesUrl);
}else {
uploadImages(imagesUrl);
}
}))
.addOnFailureListener(e -> {
Log.e("OnFailureImageListener", Objects.requireNonNull(e.getMessage()));
//some image is fails to upload
});
}
因此现在从OnActivityResult获取imageUriList
值之后,我们可以以此方式调用方法;
uploadImages(new ArrayList<>(),uriFilesList);
上传完所有图片后,您就可以在其中进行处理
private void allImageUploadedNow(ArrayList<String> imagesUrl){
//handle imagesUrl
}