如何获取正在上传的图片的Firebase下载网址?

时间:2017-06-06 14:45:05

标签: android firebase firebase-storage

我使用下面的代码将图片上传到firebase存储,但是当图片上传时,我希望能够使用下载网址调用图像。这可能吗?

ViewUserMapActivity

package uk.co.jaunt_app.jaunt;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MapStyleOptions;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.util.UUID;

import static uk.co.jaunt_app.jaunt.R.id.MapDistance;
import static uk.co.jaunt_app.jaunt.R.id.map;

public class ViewUserMapActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    Button HomeButt;
    TextView MapName;
    TextView MapStartLocLat;
    TextView MapStartLocLong;
    TextView MapEndLocLat;
    TextView MapEndLocLong;
    TextView mapDistance;
    Button chooseImg, uploadImg;
    ImageView imgView;
    int PICK_IMAGE_REQUEST = 111;
    Uri filePath;
    ProgressDialog pd;
    TextView imgUrl;

    FirebaseStorage storage = FirebaseStorage.getInstance();
    StorageReference storageRef = storage.getReferenceFromUrl("gs://jaunt-ddc86.appspot.com/");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_user_map);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(map);
        mapFragment.getMapAsync(this);

        HomeButt = (Button) findViewById(R.id.backHome);
        MapName = (TextView) findViewById(R.id.MapName);
        MapStartLocLat = (TextView) findViewById(R.id.MapStartLocLat);
        MapStartLocLong = (TextView) findViewById(R.id.MapStartLocLong);
        MapEndLocLat = (TextView) findViewById(R.id.MapEndLocLat);
        MapEndLocLong = (TextView) findViewById(R.id.MapEndLocLong);
        mapDistance = (TextView) findViewById(MapDistance);
        imgUrl = (TextView) findViewById(R.id.imgurl);

        Intent intent = getIntent();
        final String mapName = intent.getStringExtra("mapName");
        String mapStartLat = intent.getStringExtra("mapStartLat");
        String mapStartLong = intent.getStringExtra("mapStartLong");
        String mapEndLat = intent.getStringExtra("mapEndLat");
        String mapEndLong = intent.getStringExtra("mapEndLong");
        MapName.setText(mapName);
        MapStartLocLat.setText(mapStartLat);
        MapStartLocLong.setText(mapStartLong);
        MapEndLocLat.setText(mapEndLat);
        MapEndLocLong.setText(mapEndLong);


        chooseImg = (Button)findViewById(R.id.chooseImg);
        uploadImg = (Button)findViewById(R.id.uploadImg);
        imgView = (ImageView)findViewById(R.id.imgView);

        pd = new ProgressDialog(this);
        pd.setMessage("Uploading....");


        chooseImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_PICK);
                startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
            }
        });

        uploadImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(filePath != null) {
                    pd.show();
                    String imageID = UUID.randomUUID().toString();
                    StorageReference childRef = storageRef.child(imageID);

                    //uploading the image
                    UploadTask uploadTask = childRef.putFile(filePath);

                    uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            pd.dismiss();
                            Toast.makeText(ViewUserMapActivity.this, "Image Uploaded Successfully", Toast.LENGTH_LONG).show();
                        }

                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            pd.dismiss();
                            Toast.makeText(ViewUserMapActivity.this, "Upload Failed -> " + e, Toast.LENGTH_LONG).show();
                        }
                    });

                }
                else {
                    Toast.makeText(ViewUserMapActivity.this, "Select An Image", Toast.LENGTH_LONG).show();
                }
            }
        });
    }



    @Override
    protected 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 {
                //getting image from gallery
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                //Setting image to ImageView
                imgView.setImageBitmap(bitmap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        googleMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(this, R.raw.style_json));

        String mapstartlat = MapStartLocLat.getText().toString().trim();
        String mapstartlong = MapStartLocLong.getText().toString().trim();
        String mapendlat = MapEndLocLat.getText().toString().trim();
        String mapendlong = MapEndLocLong.getText().toString().trim();

        double startlat = Double.valueOf(mapstartlat);
        double startlong = Double.valueOf(mapstartlong);
        double endlat = Double.valueOf(mapendlat);
        double endlong = Double.valueOf(mapendlong);

        LatLng Start = new LatLng(startlat, startlong);
        LatLng End = new LatLng(endlat, endlong);
        mMap.addMarker(new MarkerOptions().position(Start)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.mappin)));
        mMap.addMarker(new MarkerOptions().position(End)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.mappin)));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(End, 6 ));

        Location loc1 = new Location("");
        loc1.setLatitude(startlat);
        loc1.setLongitude(startlong);

        Location loc2 = new Location("");
        loc2.setLatitude(endlat);
        loc2.setLongitude(endlong);

        float distanceInMeters = loc1.distanceTo(loc2);
        Double value = 0.00062137;
        Double distanceValue = (distanceInMeters)*value;
        mapDistance.setText(String.format("%.1f mi", distanceValue));

        HomeButt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ViewUserMapActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });

    }

}

2 个答案:

答案 0 :(得分:3)

在成功回调中使用getDownloadUrl()。上传完成后就会填充。

更多信息here

答案 1 :(得分:1)

来自Firebase documentation on uploading files

  

您可以使用putFile()方法上传设备上的本地文件,例如来自相机的照片和视频。 putFile()获取文件并返回UploadTask,您可以使用该Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg")); StorageReference riversRef = storageRef.child("images/"+file.getLastPathSegment()); uploadTask = riversRef.putFile(file); 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()) { throw task.getException(); } // Continue with the task to get the download URL return ref.getDownloadUrl(); } }).addOnCompleteListener(new OnCompleteListener<Uri>() { @Override public void onComplete(@NonNull Task<Uri> task) { if (task.isSuccessful()) { Uri downloadUri = task.getResult(); } else { // Handle failures // ... } } }); 来管理和监控上传状态。

String line = "<opr:fld name=fieldName>Value1</opr:fld>";
String regex = "(.*name=)(.*)(>.*>)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(line);
matcher.matches();
String result = matcher.group(1) + "\"" + matcher.group(2) + "\"" + matcher.group(3);
System.out.println(result);