如何在Android Studio中上传图像后将图像URL插入Firestore数据库?

huangapple go评论60阅读模式
英文:

How to insert image URL into firestore database after uploading an image in android studio?

问题

我在我的应用程序中创建了一个上传图像的功能。图像上传并显示给用户,成功后返回“已上传”。

现在,当用户关闭应用程序并重新打开时,它不会显示图像,因为图像未存储在他唯一的数据库文件中的profileImage字段中。

我正在将图像存储在存储数据存储中。

我希望将存储在存储中的相同图像网址存储在数据库中当前用户的字段中。

但是,我编写的代码仍然没有插入所需的图像网址值。

以下是我的代码:

FirebaseFirestore fStore;
FirebaseStorage storage;
StorageReference storageReference;

FirebaseAuth fAuth;
String UID;
private Uri filePath;
private final int PICK_IMAGE_REQUEST = 71;

fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);

    userImage = findViewById(R.id.profile_userImg);

    userImage.setOnClickListener(new View.OnClickListener() {
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
        @Override
        public void onClick(View view) {
            chooseImage();
        }
    });

}

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
private void chooseImage() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "选择个人资料图片"), PICK_IMAGE_REQUEST);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

        filePath = data.getData();
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
            userImage.setImageBitmap(bitmap);
            if (filePath != null) {
                StorageReference ref = storageReference.child("Users Profile/" + UUID.randomUUID().toString());
                ref.putFile(filePath).addOnSuccessListener(new OnSuccessListener <UploadTask.TaskSnapshot> () {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        UID = fAuth.getCurrentUser().getUid();
                        DocumentReference documentReference = fStore.collection("users").document(UID);
                        Map <String, Object> user = new HashMap < > ();
                        user.put("profileImage", PICK_IMAGE_REQUEST);
                        Toast.makeText(ProfileActivity.this, "已上传", Toast.LENGTH_SHORT).show();
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(ProfileActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                    }
                });

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

如果您有其他问题,请随时提出。

英文:

I created an upload image functionality in my app. The image uploads and shows for the user and returns "uploaded" upon success.

Now when the user closes the app and opens again it wont show the image because it is not stored in his unique database file in the field of profileImage.

I am storing the image in the storage datastore.

I want to store the same image url that is being stored in the storage to be in the current users field in the database.

But the code I've written still doesn't insert the required value of the image url.

Here is my code so far:

FirebaseFirestore fStore;
FirebaseStorage storage;
StorageReference storageReference;
FirebaseAuth fAuth;
String UID;
private Uri filePath;
private final int PICK_IMAGE_REQUEST = 71;
fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
userImage = findViewById(R.id.profile_userImg);
userImage.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
@Override
public void onClick(View view) {
chooseImage();
}
});
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
private void chooseImage() {
Intent intent = new Intent();
intent.setType(&quot;image/*&quot;);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, &quot;Choose a Profile Image&quot;), PICK_IMAGE_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST &amp;&amp; resultCode == RESULT_OK &amp;&amp; data != null &amp;&amp; data.getData() != null) {
filePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
userImage.setImageBitmap(bitmap);
if (filePath != null) {
StorageReference ref = storageReference.child(&quot;Users Profile/&quot; + UUID.randomUUID().toString());
ref.putFile(filePath).addOnSuccessListener(new OnSuccessListener &lt; UploadTask.TaskSnapshot &gt; () {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
UID = fAuth.getCurrentUser().getUid();
DocumentReference documentReference = fStore.collection(&quot;users&quot;).document(UID);
Map &lt; String, Object &gt; user = new HashMap &lt; &gt; ();
user.put(&quot;profileImage&quot;, PICK_IMAGE_REQUEST);
Toast.makeText(ProfileActivity.this, &quot;Uploaded&quot;, Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(ProfileActivity.this, &quot;Failed&quot;, Toast.LENGTH_SHORT).show();
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

答案1

得分: 3

文件路径不能像这样使用,作为下载图像的引用。相反,您需要获取由Firebase提供的下载URL,将您的代码更改如下:

StorageReference ref = storageReference.child("Users Profile/" + UUID.randomUUID().toString());
UploadTask uploadTask = ref.putFile(filePath);

Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
    @Override
    public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
        if (task.isSuccessful()) {
            // 图像上传完成
        }

        // 继续任务以获取下载URL
        return ref.getDownloadUrl();
    }
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
    @Override
    public void onComplete(@NonNull Task<Uri> task) {
        if (task.isSuccessful()) {
            Uri downloadUri = task.getResult(); // 这是您需要传递给数据库的下载URL
            // 将URL传递给您的引用
            UID = fAuth.getCurrentUser().getUid();
            DocumentReference documentReference = fStore.collection("users").document(UID);
            documentReference.update("profileImage", downloadUri);
            Toast.makeText(ProfileActivity.this, "已上传", Toast.LENGTH_SHORT).show();
        } else {
            // 处理失败
            // ...
        }
    }
});

您可以在此处查看更详细的信息:https://firebase.google.com/docs/storage/android/upload-files#java_1

英文:

The file path cannot be used like that, as a reference to download an image. Instead you need to get a download url that is provided by firebase, change your code like this:

 StorageReference ref = storageReference.child(&quot;Users Profile/&quot; + UUID.randomUUID().toString());
UploadTask uploadTask = ref.putFile(filePath);
Task&lt;Uri&gt; urlTask = uploadTask.continueWithTask(new Continuation&lt;UploadTask.TaskSnapshot, Task&lt;Uri&gt;&gt;() {
@Override
public Task&lt;Uri&gt; then(@NonNull Task&lt;UploadTask.TaskSnapshot&gt; task) throws Exception {
if (task.isSuccessful()) {
//here the upload of the image finish
}
// Continue the task to get a download url
return ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener&lt;Uri&gt;() {
@Override
public void onComplete(@NonNull Task&lt;Uri&gt; task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult(); //this is the download url that you need to pass to your database
//Pass the url to your reference
UID = fAuth.getCurrentUser().getUid();
DocumentReference documentReference = fStore.collection(&quot;users&quot;).document(UID);
documentReference.update(&quot;profileImage&quot;, downloadUri);
Toast.makeText(ProfileActivity.this, &quot;Uploaded&quot;, Toast.LENGTH_SHORT).show();
} else {
/ Handle failures
// ...
}
}
});

You can see in more detail here: https://firebase.google.com/docs/storage/android/upload-files#java_1

答案2

得分: 0

你的代码实际上没有向你创建的 DocumentReference 写入任何内容。 你需要调用 set()

DocumentReference documentReference = fStore.collection("users").document(UID);
documentReference.set(...)

你需要传递一个对象或映射给 set(),以告诉它要存储在文档中的内容,如文档所示。

英文:

Your code doesn't actually write anything to the DocumentReference you created. You will need a call to set():

DocumentReference documentReference = fStore.collection(&quot;users&quot;).document(UID);
documentReference.set(...)

You will need to pass an object or Map to set to tell it what to store in the document, as illustrated in the documentation.

答案3

得分: 0

storageRef.child(path).getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
    @Override
    public void onSuccess(Uri uri) {
        Glide.with(getApplicationContext()).load(uri.toString()).into(img);
    }
});
英文:
storageRef.child(path).getDownloadUrl().addOnSuccessListener(new OnSuccessListener&lt;Uri&gt;() {
@Override
public void onSuccess(Uri uri) {
Glide.with(getApplicationContext()).load(uri.toString()).into(img);
}
});

huangapple
  • 本文由 发表于 2020年8月9日 01:58:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/63318634.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定