Android
안드로이드 파이어베이스 스토리지에 사진 저장
joong~
2019. 6. 1. 01:47
728x90
앨범에서 사진을 골라오면 해당 사진 파일경로를 따와서 파이어베이스 스토리지에 저장하는 것을 정리 한다.
우선 앨범에서 선택한 이미지(get.data)를 String 변수에 할당했다.
String path = getPath(data.getData()); 로 받았다
System.out.println(get.data()); 를 했을때 코드는 content://com.google.android.apps~~~~~~~~로 나오는데
아래 코드는 Content의 Uri 을 FilePath로 바꾸는 코드이다
// uri 절대경로 가져오기
public String getPath(Uri uri){
String [] proj = {MediaStore.Images.Media.DATA};
CursorLoader cursorLoader = new CursorLoader(this,uri,proj,null,null,null);
Cursor cursor = cursorLoader.loadInBackground();
int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(index);
}
System.out.println(getPath(data.getData())); 를 해보면 절대경로로 나오는걸 볼수 있을 것이다.
이제 이 파일을 스토리지에 올려보자
StorageReference storageRef = mStorage.getReference();
Uri file = Uri.fromFile(new File(Uripath)); // 절대경로uri를 file에 할당
Log.d(TAG, "photo file : " + file);
// stroage images에 절대경로파일 저장
StorageReference riversRef = storageRef.child("images/" + file.getLastPathSegment());
UploadTask uploadTask = riversRef.putFile(file);
Log.d(TAG, "uploadTask : " + uploadTask);
// Register observers to listen for when the download is done or if it fails
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
PostModel postModel = new PostModel();
postModel.myid = contentsUid;
postModel.contents = c;
postModel.location = l;
postModel.person = f;
postModel.photo = Uripath;
// 게시글 내용 저장
mDatabase.getReference().child("contents").child("content").push()
.setValue(postModel).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
//
}
});
}
});
이미지의 절대경로 파일은 Uripath이다.(다른액티비티에서 putextra로 보냈다)
이미지는 절대경로로 스토리지에 저장 하였고, 저장이 성공하면 게시글들의 내용을 db에 저장한 코드이다.