java - 如何将 android 中转换后的 drawable 上传到 Firebase?
问题描述
在我的应用程序中,我能够正确地将可绘制对象转换为图像并将其保存在本地设备上。但是,我需要将图像推送到 Firebase,而不是将其保存在本地。这就是我所做的。
public void saveImage () {
int count = 0;
File sdDirectory = Environment.getExternalStorageDirectory();
File subDirectory = new File(sdDirectory.toString() + "/Pictures/Paint");
if (subDirectory.exists()) {
File[] existing = subDirectory.listFiles();
for (File file : existing) {
if (file.getName().endsWith(".jpg") || file.getName().endsWith(".png")) {
count++;
}
}
} else {
subDirectory.mkdir();
}
if (subDirectory.exists()) {
File image = new File(subDirectory, "/drawing_" + (count + 1) + ".png");
FileOutputStream fileOutputStream;
try {
fileOutputStream = new FileOutputStream(image);
//The code below still doesn't save the image online in firebase.
Uri file = Uri.fromFile(image);
// StorageReference fileRef = reference.child(System.currentTimeMillis() + "." + getFileExtension(file));
StorageReference fileRef = reference.child(System.currentTimeMillis() + ".png");
fileRef.putFile(file).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
Model model = new Model(uri.toString());
String modelId = root.push().getKey();
root.child(modelId).setValue(model);
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(getContext(), "Uploaded Successfully!", Toast.LENGTH_SHORT).show();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getContext(), "Uploading Failed!", Toast.LENGTH_SHORT).show();
}
});
Boolean bool = mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
Toast.makeText(getContext(), "saved locally", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
}
它总是无法上传文件,但它成功地将其保存在本地。我什至只是尝试在成功上传后显示通知,但它甚至没有到达addOnSuccessListener少谈onSuccessMethod。我觉得我很接近,但我做错了什么?
解决方案
您的代码忽略了各种错误,这让您(更不用说我们)很难排除故障。
首先:停止捕获错误并且对它们不做任何事情,例如在} catch (FileNotFoundException e) {
. 至少你应该用以下方式记录它们:
Log.e("Storage", "Error uploading image", e)
对于IOException
, 和public void onFailure(@NonNull Exception e) {
: 也是如此,如果您也在那里登录e
,您可能能够找到(在您的 logcat 输出中)出了什么问题。
推荐阅读
- reactjs - React-redux 错误“道具 `store` 在 `Root` 中被标记为必需,但它的值是 `undefined”
- amazon-web-services - 在 AWS CodeCommit 上上传代码时出错
- c++ - 为什么我们使用 enable_shared_from_this 模板?
- angular - 类型上不存在属性“订阅”。甚至返回 Observable
- c - 多线程嵌入式软件中的原子操作
- python - 用字符串替换整数区间
- azure - 基于 blob 触发 VSTS/TFS 构建
- shell - 如何使用 getopts 声明一个不允许任何参数的选项
- python - 保持从 for loop pandas 返回的迭代项的索引
- javascript - 在 html 页面中显示文件内容会产生空字段