我如何将多张图片上传到Firebase

问题描述 投票:0回答:1

我想将多张图片上传到Firebase,并获得指向Firestore数据库的url链接。但是我只能通过字节上传单个图像。我应该在firebase中使用putFile而不是putBytes吗?需要帮助,谢谢!

我的获取图像路径的代码

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = image.getAbsolutePath();
    return image;
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    /*
        Results when selecting new image from phone memory
     */
    if(requestCode == PICKFILE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {

        ClipData clipData = data.getClipData();
        if (clipData != null) {
            for (int i = 0; i < clipData.getItemCount(); i++) {
                Uri selectedImageUri = clipData.getItemAt(i).getUri();
                Log.d(TAG, "onActivityResult: images: " + selectedImageUri);
                //send the bitmap and fragment to the interface
                mOnPhotoReceived.getImagePath(selectedImageUri);
                getDialog().dismiss();
            }
        } else {
        Uri selectedImageUri = data.getData();
        Log.d(TAG, "onActivityResult: image: " + selectedImageUri);

        //send the bitmap and fragment to the interface
        mOnPhotoReceived.getImagePath(selectedImageUri);
        getDialog().dismiss();

        }
    }

    else if(requestCode == CAMERA_REQUEST_CODE && resultCode == Activity.RESULT_OK){

        Log.d(TAG, "onActivityResult: image uri: " + mCurrentPhotoPath);
        mOnPhotoReceived.getImagePath(Uri.fromFile(new File(mCurrentPhotoPath)));
        getDialog().dismiss();
    }


}

@Override
public void onAttach(Context context) {
    try{
        mOnPhotoReceived = (OnPhotoReceivedListener) getActivity();
    }catch (ClassCastException e){
        Log.e(TAG, "onAttach: ClassCastException", e.getCause() );
    }
    super.onAttach(context);
}

要上传到firebase的代码和要上传到firestore的代码

@Override
public void getImagePath(Uri imagePath) {
        mAttachments.add(imagePath.toString());
        Log.d(TAG, "getImagePath: uri: " + imagePath.toString());
        initRecyclerImageView();
        mAttachmentRecyclerViewAdapter.notifyDataSetChanged();
        uploadNewPhoto(imagePath);
}

/**
 * Uploads a new Item photo to Firebase Storage using a @param ***imageUri***
 * @param imageUri
 */
public void uploadNewPhoto(Uri imageUri){
    Log.d(TAG, "uploadNewPhoto: uploading new image." + imageUri);


    //Only accept image sizes that are compressed to under 5MB. If thats not possible
    //then do not allow image to be uploaded
    if(mConvert != null){
        mConvert.cancel(true);
    }
    mConvert = new BackgroundConversion();
    mConvert.execute(imageUri);
    Log.d(TAG, "uploadNewPhoto: ImageUri's: "+ imageUri);
}



public class BackgroundConversion extends AsyncTask<Uri, Integer, byte[]> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected byte[] doInBackground(Uri... params) {
        Log.d(TAG, "doInBackground: started.");

        InputStream iStream = null;
        try {
            iStream = getApplicationContext().getContentResolver().openInputStream(params[0]);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];

        int len = 0;
        try {
            while ((len = iStream.read(buffer)) != -1) {
                byteBuffer.write(buffer, 0, len);
            }
            iStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return byteBuffer.toByteArray();
    }

    @Override
    protected void onPostExecute(byte[] bytes) {
        super.onPostExecute(bytes);
        mBytes = bytes;
        Log.d(TAG, "onPostExecute: Bytes: " + bytes);

    }
}

public void executeUploadTask() {
    FilePaths filePaths = new FilePaths();
    //specify where the photo will be stored

    String uploadPath = "";
    String format = "";

    SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
    format = s.format(new Date());

    uploadPath = filePaths.FIREBASE_ITEMS_IMAGE_STORAGE + "/" + "Fruits"
            + "/image_" + format;
    final String imageName = "image_" + format;


    for (int i = 0; i < mAttachments.size(); i++) {
        int finalI = i;
        String nameimage = mAttachments.get(i);
        Log.d(TAG, "executeUploadTask: Image :" + nameimage);}
        final StorageReference storageReference = FirebaseStorage.getInstance().getReference()
                .child(uploadPath);

        if (mBytes.length / MB < MB_THRESHHOLD) {

            // Create file metadata including the content type
            StorageMetadata metadata = new StorageMetadata.Builder()
                    .setContentType("image/jpg")
                    .setContentLanguage("en")
                    .build();
            //if the image size is valid then we can submit to database
            UploadTask uploadTask = storageReference.putBytes(mBytes, metadata);


            uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                    storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri uri) {
                            final Uri firebaseURL = uri;
                            Log.d(TAG, "onSuccess: firebase download url : " + firebaseURL.toString());


                            FirebaseFirestore df = FirebaseFirestore.getInstance();
                            DocumentReference newIssueRef = df
                                    .collection("fruits & vegetables")
                                    .document("UyGXpk2n1A6mHsUcYjCi")
                                    .collection("Organic Fruits")
                                    .document();
                            itemId = newIssueRef.getId();
                            Attachment item = new Attachment();

                            item.setItem_name(edit_name.getText().toString());
                            item.setItem_brand(edit_brand.getText().toString());
                            item.setItem_price(edit_price.getText().toString());
                            item.setItem_about(edit_about.getText().toString());
                            item.setItem_id(itemId);

                            item.setUrl(firebaseURL.toString());
                            newIssueRef.set(item).addOnSuccessListener(new OnSuccessListener<Void>() {
                                @Override
                                public void onSuccess(Void aVoid) {
                                    Snackbar.make(findViewById(android.R.id.content),
                                            "Successfully Uploaded :)", Snackbar.LENGTH_LONG).show();
                                    edit_name.setText("");
                                    edit_about.setText("");
                                    edit_brand.setText("");
                                    edit_price.setText("");
                                    updatedImage.setImageResource(R.drawable.ic_android);
                                    progressBar2.setVisibility(View.INVISIBLE);
                                }
                            }).addOnFailureListener(new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception e) {
                                    Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                    });

                }

            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    Toast.makeText(mContext, "error uploading image", Toast.LENGTH_SHORT).show();

                }
            }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                    double currentProgress = (100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                    if (currentProgress > (progress + 15)) {
                        progress = (100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                        Log.d(TAG, "onProgress: Upload is " + progress + "% done");
                    }

                }
            });
        } else {
            Toast.makeText(mContext, "Image is too Large", Toast.LENGTH_SHORT).show();
        }
    }
}
android firebase android-studio google-cloud-firestore
1个回答
0
投票

如果您要上传本地文件,我建议您使用putFile()。文档Upload Files on Android为您提供了如何在Android上上传文件的示例。

[除此之外,我可以从社区中找到一些不错的帖子,您可以在其中找到示例以及有关如何实现多重文件上传的更多说明。 Uploading multiple images to firebase and getting links of all of them这是一个更具体的名称,它还可以帮助从文件生成链接。

以下两个,应该可以帮助您配置和设置应用程序以在Firebase上上传多个文件。

让我知道信息是否对您有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.