如何上传图片Url上传到Fire Storage并同时保存在fireStore中使用Java

Posted

技术标签:

【中文标题】如何上传图片Url上传到Fire Storage并同时保存在fireStore中使用Java【英文标题】:how to upload image Url Uploaded to Fire Storage and Save it in fireStore at the Same time Using Java 【发布时间】:2020-09-01 17:00:50 【问题描述】:

这是我的代码,我可以在其中检索 Toast 消息中的图像 URL,但它无法将其保存在 Firestore 中,请告诉我是否有其他方法可以做到这一点,或者是我存储 URL 的问题:

public class register extends AppCompatActivity 

     EditText emails;
    EditText passwords;
    EditText ages;
    Button registers;
    Button addImage;
    EditText country;

    FirebaseFirestore db;
    FirebaseAuth auth;
    FirebaseUser auth1;
    private StorageTask task;

    Uri url ;
    Uri imageUri;

    static final int IMAGE_REQUEST =2;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);


        auth = FirebaseAuth.getInstance();
        registers = findViewById(R.id.button);
        emails = findViewById(R.id.eamil);
        passwords = findViewById(R.id.password);
        ages=findViewById(R.id.age);
        country=findViewById(R.id.country);
        addImage = findViewById(R.id.button51);

         db =FirebaseFirestore.getInstance();





             registers.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                String v_email = emails.getText().toString();
                String v_password = passwords.getText().toString();


                if (TextUtils.isEmpty(v_email)||TextUtils.isEmpty(v_password))

                    Toast.makeText(register.this,"Eempty Credentials",Toast.LENGTH_SHORT).show();
                else if(v_password.length()<6)

                    Toast.makeText(register.this,":password is short",Toast.LENGTH_SHORT).show();

                else









                        upload();
                        registerUser(v_email, v_password);




                
            
        );

             addImage.setOnClickListener(new View.OnClickListener() 
                 @Override
                 public void onClick(View v) 

                     openImage();

                 
             );



    

    private void registerUser(final String email, final String password) 

        auth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(register.this, new OnCompleteListener<AuthResult>() 
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) 

                if(task.isSuccessful())


                    Map<String , Object> users = new HashMap<>();
                    users.put("Email", emails.getText().toString());
                    users.put("Password", passwords.getText().toString());
                    users.put("Country", country.getText().toString());
                    users.put("AGe", ages.getText().toString());
                    users.put("Image", url.toString());
                    auth1 = FirebaseAuth.getInstance().getCurrentUser();
                    db.collection("Users").document(auth1.getUid()).set(users).addOnCompleteListener(new OnCompleteListener<Void>() 
                        @Override
                        public void onComplete(@NonNull Task<Void> task) 

                            //Toast.makeText(com.example.pleasework.register.this,"registeration was successful",Toast.LENGTH_SHORT).show();

                        
                    );



//                    startActivity(new Intent(com.example.pleasework.register.this, MainActivity.class));
//                    finish();


                else


                    Toast.makeText(com.example.pleasework.register.this,"Resgisteration fail",Toast.LENGTH_SHORT).show();
                
            
        );


    
    public  String getFileExtension(Uri uri)

        ContentResolver contentResolver = getContentResolver();
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();

        return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));



    

   public void  upload ()

        if (imageUri != null)


            final StorageReference fileRef  = FirebaseStorage.getInstance().getReference(System.currentTimeMillis()+getFileExtension(imageUri) );

            fileRef.putFile(imageUri)
                    .addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() 
                        @Override
                        public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) 

                            fileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() 
                                @Override
                                public void onSuccess(Uri uri) 

                                    url = uri;
                                    Toast.makeText(register.this,"Upload Sucess" + url.toString(),Toast.LENGTH_SHORT).show();

                                
                            );

                        
                    );


        


    

    public  void openImage()

        Intent intent = new Intent();
        intent.setType("image/");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent,IMAGE_REQUEST);

    

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) 
        super.onActivityResult(requestCode, resultCode, data);
        imageUri=data.getData();

    





            
        );
    



并且在火存储中,该字段始终为空,但它保存在火存储中。

想为 FireStore 添加图像,但没有

谢谢。

【问题讨论】:

【参考方案1】:

这个进程叫做AsyncTask,意在在一个进程之前执行一个进程。

可以同时上传图片和数据,所以图片链接没有保存,因为它没有完成图片上传,不到一秒。

您可以在图片上传完成后使用此方法,数据存储在 FireStore 中:

   private void registerUser(final String email, final String password) 

            auth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(register.this, new OnCompleteListener<AuthResult>() 
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) 

                    if(task.isSuccessful())
                       upload ();
                    
);

这里一定要先上传图片,再将ImageUrl添加到fireStore:

public void  upload ()

        if (imageUri != null)


            final StorageReference fileRef  = FirebaseStorage.getInstance().getReference(System.currentTimeMillis()+getFileExtension(imageUri) );

            fileRef.putFile(imageUri)
                    .addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() 
                        @Override
                        public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) 

                            fileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() 
                                @Override
                                public void onSuccess(Uri uri) 

                                    url = uri;

                                Map<String , Object> users = new HashMap<>();
                                users.put("Email", emails.getText().toString());
                                users.put("Password", passwords.getText().toString());
                                users.put("Country", country.getText().toString());
                                users.put("AGe", ages.getText().toString());
                                users.put("Image", url.toString());
                                auth1 = FirebaseAuth.getInstance().getCurrentUser();

                    db.collection("Users").document(auth1.getUid()).set(users).addOnCompleteListener(new OnCompleteListener<Void>() 
                        @Override
                        public void onComplete(@NonNull Task<Void> task) 

                             Toast.makeText(register.this,"Upload Sucess" + url.toString(),Toast.LENGTH_SHORT).show();

                             
                         );

                       
                   );
                
            ); 
        

    

【讨论】:

以上是关于如何上传图片Url上传到Fire Storage并同时保存在fireStore中使用Java的主要内容,如果未能解决你的问题,请参考以下文章

azure storage上传图片文件并获取其url以显示img标签

为啥图片没有上传到 Firebase-storage 并破解?

Flutter:Fire Base 存储图像上传的后期初始化错误

我应该将图片上传到 Cloud Firestore 还是 Firebase Storage?

从 Fire Storage 检索图像,但是如果图像不存在,则应用程序崩溃

如何更改图片上传目录并在 laravel 中查看图片 url