将多个图像上传到firebase存储

qaxu7uf2  于 2023-02-16  发布在  其他
关注(0)|答案(5)|浏览(143)

我使用firebase构建了一个聊天应用程序,并希望将多个图像发送到firebase存储。
使用此库
编译"com.github.darsh2:多个图像选择:3474549"
在顶端

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();
            }
        });

活动结果

if (requestCode == Constants.REQUEST_CODE && resultCode == RESULT_OK) {
        ArrayList<Image> images = data.getParcelableArrayListExtra(Constants.INTENT_EXTRA_IMAGES);
        Uri uri = Uri.parse(String.valueOf(images));
        storageRef = storage.getReference("photos");
        final StorageReference photoRef = storageRef.child(uri.getLastPathSegment());
        photoRef.putFile(uri)
                .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);
                        }
                    }
                });

    }
myzjeezk

myzjeezk1#

  • 变量 *
  • 私有静态最终整数PICK_IMAGE = 1;
  • 按钮选择器Btn、上传器Btn;
  • 文本视图警报;
  • 私有Uri图像Uri;
  • 数组列表图像列表=新建数组列表();
  • 私有整数上载计数= 0;
  • 私有进度对话进度对话;
  • 数组列表urlString;
  • 创建()*
@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();
}
  • 在活动结果()上 *
@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();
            }

        }
    }
}

}

ht4b089n

ht4b089n2#

它工作正常。

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);
                            }
                        }
                    });

        }

    }
juud5qan

juud5qan3#

对于返回列表imageUrls与从库中选择的图像具有相同顺序,不要对每个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
}
hfsqlsce

hfsqlsce4#

这个工具类我创建它上传多个图像到firebase存储使用Kotlin与协程的帮助。如果你有任何增强请告诉我。
你需要先添加这些依赖项。
实现'com.google.firebase:防火墙存储-ktx:19.1.1'
//Firebase通过kotlinx-coroutines-play-serviceslibrary向协程添加支持
实现“org.jetbrains.kotlinx:kotlinx协同程序播放服务:1.3.1”
有关详细信息,请检查linkgithub 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()
    }
}
eoxn13cs

eoxn13cs5#

In my case of uploading multiple images into firebase I have used forEach(). forEach() method had helped me to upload images successfully into firebase


import { getStorage, ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";
const Product =()=>{
const [file, setFile] =useState([])
Object.values(file).forEach(val => {
const storage = getStorage();
const storageRef = ref(storage, 'images/val.name');

const uploadTask = uploadBytesResumable(storageRef, val);
uploadTask.on('state_changed', 
  (snapshot) => {
     number of bytes to be uploaded
    const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
    console.log('Upload is ' + progress + '% done');
    switch (snapshot.state) {
      case 'paused':
        console.log('Upload is paused');
        break;
      case 'running':
        console.log('Upload is running');
        break;
    }
  }, 
  (error) => {
  }, 
  () => {
    getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
      console.log('File available at', downloadURL);
    });
  }
);
})
return (
<button onClick={(e) => setFile(e.target.files)}/>
)
}

相关问题