Я хотел загрузить несколько изображений в Firebase и получить URL-ссылку на базу данных Firestore. но я могу загрузить только одно изображение через байты. я должен go для putFile вместо putBytes в Firebase. нужна помощь, спасибо!
мой код для получения пути к изображению
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 и URL для 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();
}
}
}