본문 바로가기
안드로이드+자바

파이어베이스 storage 사용하는 코드

by 문자메일 2017. 1. 15.

//스트림에서 업로드
firebaseStorage = FirebaseStorage.getInstance(); //저장소 인스턴스 가져오기
rootReference = firebaseStorage.getReferenceFromUrl("gs://realtimedatabase-3d54a.appspot.com");
StorageReference imageReference = rootReference.child("images"); //create a reference to "mountauns.jpg"
StorageReference mountainImageRef = rootReference.child("images/mountains.jpg");

InputStream stream = null;
try {
stream = new FileInputStream(new File("/storage/emulated/0/Pictures/KakaoTalk/1484276153455.JPEG"));
uploadTask = imageReference.child(stream.toString()).putStream(stream);
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) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
Uri downloadUrl = taskSnapshot.getDownloadUrl();
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "예외발생!!!", Toast.LENGTH_SHORT).show();
}


//로컬 파일에서 업로드
firebaseStorage = FirebaseStorage.getInstance();
rootReference = firebaseStorage.getReferenceFromUrl("gs://realtimedatabase-3d54a.appspot.com");
StorageReference reference = rootReference.child("picture");

Uri file = Uri.fromFile(new File("/storage/emulated/0/Pictures/KakaoTalk/1484276153455.JPEG"));
StorageReference riversRef = reference.child(file.getLastPathSegment()); //picture 하위에 파일의 getLastPathSegment가 참조하는 곳에 이미지 저장
uploadTask = riversRef.putFile(file);

uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(MainActivity.this, "이미지 업로드 실패", Toast.LENGTH_SHORT).show();
}
});
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "이미지 업로드 성공", Toast.LENGTH_SHORT).show();
}
});


댓글