将图像上传到Firebase存储并在Firebase数据库中具有链接

时间:2018-11-28 03:55:56

标签: java android firebase firebase-realtime-database firebase-storage

我目前正在使用“事件报告”应用程序,该应用程序允许用户选择和上传图像。

我已经成功地将图像发布到Firebase Storage,但是我想知道Firebase数据库中是否可以有一个链接/ URL,我可以单击该链接/ URL以将我重定向到Firebase Storage以查看该图像。

我想要此功能,以便最终用户能够连同标题,日期,备注等用户输入一起看到带有链接的“图像”子项和其他输入

我曾尝试在StackOverflow和Youtube上搜索答案,但其中大多数都已过时并且看起来已经过时。有一个命令“ getDownloadUrl”,但我认为它已被弃用。

这是我班上的代码,它将我的图像上传到Firebase存储

  private void uploadImage() {

    if (filePath != null) {

        final ProgressDialog progressDialog = new ProgressDialog(getActivity());
        progressDialog.setTitle("Uploading...");
        progressDialog.show();

        StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
        ref.putFile(filePath)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        progressDialog.dismiss();
                        Toast.makeText(getActivity(),"Uploaded", Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        progressDialog.dismiss();
                        Toast.makeText(getActivity(),"Failed"+e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                        double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
                        progressDialog.setMessage("Uploaded"+(int)progress+"%");
                    }
                });
    }
}

private void chooseImage() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent,"Select Picture"),PICK_IMAGE_REQUEST);
}

ReportFragment

import static android.app.Activity.RESULT_OK;
import static com.firebase.ui.auth.AuthUI.getApplicationContext;

public class ReportFragment extends Fragment implements 
AdapterView.OnItemSelectedListener{

private Button btnChoose,btnUpload;
private ImageView imageView;
private Uri filePath;
private final int PICK_IMAGE_REQUEST = 71;
private TextView mDisplayDate;
private DatePickerDialog.OnDateSetListener mDateSetListener;

private EditText reportedBy;
private TextView date; //upstairs declare alr as mDisplayDate
private Spinner spinner; //downstairs declare alr as spinner3
private EditText location;
private Spinner spinner2; //downstairs declare alr as spinner2
private EditText details;
private Spinner spinner3; //downstairs declare alr as spinner1
private EditText remarks;
private EditText title;
private Button submitIncident;


public static TextView resultTextView3;
Button scan_btn3;

private ImageView imageView2;
private TextView imgUrl1;

DatabaseReference databaseIncidents;
FirebaseStorage storage;
StorageReference storageReference;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable 
ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_report, container, false);

    databaseIncidents = 
FirebaseDatabase.getInstance().getReference("Incidents");
    storage = FirebaseStorage.getInstance();
    storageReference = storage.getReference();

    btnChoose = (Button) v.findViewById(R.id.btnChoose);
    btnUpload = (Button) v.findViewById(R.id.btnUpload);
    imageView = (ImageView) v.findViewById(R.id.imgView);

    reportedBy = (EditText) v.findViewById(R.id.etreportedby);
//        Below have already line 151
//        date = (TextView) v.findViewById(R.id.tvdate);
    location = (EditText) v.findViewById(R.id.etlocation);
    details = (EditText) v.findViewById(R.id.etdetails);
    remarks = (EditText) v.findViewById(R.id.etremarks);
    title = (EditText) v.findViewById(R.id.ettitle);
    submitIncident = (Button) v.findViewById(R.id.btnSubmit);


    resultTextView3 = (TextView)v.findViewById(R.id.result_text3);
    scan_btn3 = (Button)v.findViewById(R.id.btn_scan3);

    imageView2 = (ImageView)v.findViewById(R.id.ivimagescardinput);
    imgUrl1 = (TextView)v.findViewById(R.id.tvimagescard);






    btnChoose.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            chooseImage();
        }
    });
//        btnUpload.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                uploadImage();
//            }
//        });


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

            startActivity(new 
Intent(getActivity(),ScanCodeActivity.class));

        }
    });

    submitIncident.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            incidentSubmit();
            uploadImage();

            Glide.with(getActivity()).load(URL).into(imageView2);
        }
    });

    return`


}

private void incidentSubmit(){
    String reportedname = reportedBy.getText().toString().trim();
    String location1 = location.getText().toString();
    String details1 = details.getText().toString();
    String remarks1 = remarks.getText().toString();
    String urgency1 = spinner.getSelectedItem().toString();
    String type1 = spinner2.getSelectedItem().toString();
    String splocation1 = spinner3.getSelectedItem().toString();
    String date1 = mDisplayDate.getText().toString();
    String title1 = title.getText().toString();
    String qrlocation1 = resultTextView3.getText().toString();
    String image1 = imgUrl1.getText().toString();


    if(!TextUtils.isEmpty(reportedname)) {

        String incidentId = databaseIncidents.push().getKey();
        Incident incident = new 



Incident(reportedname,location1,details1,remarks1,urgency1,type1,splocation1,date1,title1,qrlocation1,image1);
            databaseIncidents.child(incidentId).setValue(incident);

            Toast.makeText(getActivity(), "Incident Added", Toast.LENGTH_LONG).show();
            FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container, new IncmanFragment());
            fragmentTransaction.commit();
            } else {
            Toast.makeText(getActivity(), "All fields must be entered",Toast.LENGTH_LONG).show();
        }
    }
private void uploadImage() {


    if (filePath != null) {

        final StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());

       ref.putFile(filePath).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
           @Override
           public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
               if(task.isSuccessful()) {
                   ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                       @Override
                       public void onSuccess(Uri uri) {
                           String URL = uri.toString();
                           databaseIncidents.child("imageId").setValue(URL.toString());

                       }

                   });

               }

           }

       });

    }


}


private void chooseImage() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent,"Select Picture"),PICK_IMAGE_REQUEST);
}



@Override
public void onActivityResult(int requestCode, int resultCode, 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(getActivity().getApplicationContext().getContentResolver(),filePath);
            imageView.setImageBitmap(bitmap);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    String text = parent.getItemAtPosition(position).toString();
    Toast.makeText(parent.getContext(), text, Toast.LENGTH_SHORT).show();
}

@Override
public void onNothingSelected(AdapterView<?> parent) {

}
}

非常感谢任何帮助或教程!

Database Inputs (not including image)

2 个答案:

答案 0 :(得分:0)

要将图像存储到Firebase存储中,首先要设置正确的引用,然后将图像存储在其中,这与Firebase数据库数据存储非常相似。

要在Firebase数据库中具有链接,您只需使用downloadUri即可从存储中获取并将其存储在数据库中。

此代码看起来像这样,您可以从中获得启发,并提供更适合您的代码:

private void uploadFile(Bitmap bitmap) {

        FirebaseStorage storage = FirebaseStorage.getInstance();
        final StorageReference storageRef = storage.getReference();

        final StorageReference ImagesRef = storageRef.child("images/"+mAu.getCurrentUser().getUid()+".jpg");


        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
        byte[] data = baos.toByteArray();
        final UploadTask uploadTask = ImagesRef.putBytes(data);



        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                Log.i("whatTheFuck:",exception.toString());
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
                // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.

                Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                    @Override
                    public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) {
                        if (!task.isSuccessful()) {
                            Log.i("problem", task.getException().toString());
                        }

                        return ImagesRef.getDownloadUrl(); 
                    }
                }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                    @Override
                    public void onComplete(@NonNull Task<Uri> task) {
                        if (task.isSuccessful()) {
                            Uri downloadUri = task.getResult();

                            DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users").child(mAu.getCurrentUser().getUid());

                            Log.i("seeThisUri", downloadUri.toString());// This is the one you should store

                            ref.child("imageURL").setValue(downloadUri.toString());


                        } else {
                            Log.i("wentWrong","downloadUri failure");
                        }
                    }
                });
             }
        });

    }

答案 1 :(得分:0)

如果我理解正确,则可以成功将图像上传到存储设备,但是在获取该图像直接URL时遇到了麻烦。

尝试以下代码:

StorageReference storageRef=FirebaseStorage.getInstance().getReference().child("images/"+ UUID.randomUUID().toString());
    storageRef.putFile(filePath).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
            if(task.isSuccessful()){
                storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        String URL = uri.toString();
                        //This is your image url do whatever you want with it.
                    }
                });
            }     
        }
    });