我有一个脚本,可以很好地用于上传图像,然后将其显示在我的应用程序上。这是我的完整代码:
public class MainActivity extends AppCompatActivity {
private StorageReference mStorageRef;
Button btnPickImage, btnUpload, buttonDownload;
ImageView imgSource, imgDestination;
LinearLayout lv;
Uri selectedImage;
ProgressBar pbbar;
DatabaseReference databaseReference, childReference;
private static final int REQUEST_TAKE_GALLERY_PHOTO = 2;
StorageReference fireRef;
private FirebaseAuth mAuth;
FirebaseUser currentUser;
String imageURL = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
pbbar = findViewById(R.id.pbbar);
pbbar.setVisibility(View.GONE);
lv = findViewById(R.id.lv);
mStorageRef = FirebaseStorage.getInstance().getReference();
databaseReference = FirebaseDatabase.getInstance().getReference();
btnPickImage = findViewById(R.id.btnPickImage);
btnUpload = findViewById(R.id.btnUpload);
buttonDownload = findViewById(R.id.btnDownload);
buttonDownload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//justDownloadWithoutUploading();
}
});
imgSource = findViewById(R.id.imgSource);
imgDestination = findViewById(R.id.img);
btnPickImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)
&& !Environment.getExternalStorageState().equals(
Environment.MEDIA_CHECKING)) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_TAKE_GALLERY_PHOTO);
} else
Toast.makeText(MainActivity.this, "No gallery found.", Toast.LENGTH_SHORT).show();
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
UploadImages();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_TAKE_GALLERY_PHOTO) {
Bitmap originBitmap = null;
selectedImage = data.getData();
InputStream imageStream;
try {
pbbar.setVisibility(View.VISIBLE);
imageStream = getContentResolver().openInputStream(
selectedImage);
originBitmap = BitmapFactory.decodeStream(imageStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (originBitmap != null) {
{
this.imgSource.setImageBitmap(originBitmap);
pbbar.setVisibility(View.GONE);
imgSource.setVisibility(View.VISIBLE);
}
} else
selectedImage = null;
}
}
}
public String GetDate() {
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String currentdate = df.format(Calendar.getInstance().getTime());
return currentdate;
}
public void UploadImages() {
try {
pbbar.setVisibility(View.VISIBLE);
lv.setVisibility(View.GONE);
String strFileName = GetDate() + "img.jpg";
Uri file = selectedImage;
fireRef = mStorageRef.child("images/" + currentUser.getUid().toString() + "/" + strFileName);
UploadTask uploadTask = fireRef.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();
}
//return fireRef.getDownloadUrl();
Toast.makeText(MainActivity.this, "Calling method!", Toast.LENGTH_LONG).show();
return downloadImage(fireRef);
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
Log.e("Image URL", downloadUri.toString());
pbbar.setVisibility(View.GONE);
selectedImage = null;
imageURL = downloadUri.toString();
} else {
Toast.makeText(MainActivity.this, "Image upload unsuccessful. Please try again.", Toast.LENGTH_LONG).show();
}
pbbar.setVisibility(View.GONE);
lv.setVisibility(View.VISIBLE);
DownloadImageFromURL downloadImageFromURL = new DownloadImageFromURL();
downloadImageFromURL.execute("");
}
});
} catch (Exception ex) {
Toast.makeText(MainActivity.this, ex.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}
private class DownloadImageFromURL extends AsyncTask<String, Void, String> {
Bitmap bitmap = null;
@Override
protected void onPreExecute() {
}
protected String doInBackground(String... urls) {
try {
Log.e("imageURL is ", imageURL);
InputStream in = new java.net.URL(imageURL).openStream();
if (in != null) {
bitmap = BitmapFactory.decodeStream(in);
} else
Log.e("Empty InputStream", "InputStream is empty.");
} catch (MalformedInputException e) {
Log.e("Error URL", e.getMessage().toString());
} catch (Exception ex) {
Log.e("Input stream error", "Input stream error");
}
return "";
}
protected void onPostExecute(String result) {
if (bitmap != null) {
imgDestination.setImageBitmap(bitmap);
} else
Log.e("Empty Bitmap", "Bitmap is empty.");
}
}
public Task<Uri> downloadImage(StorageReference fireRef){
Toast.makeText(MainActivity.this, "THIS METHOD GOT CALLED.", Toast.LENGTH_LONG).show();
return fireRef.getDownloadUrl();
}}
但是,我添加了一个额外的按钮来仅下载图片(不能上传!),但是我在努力做到这一点。我为此制作了一个名为“ justDownloadWithoutUploading”的方法
代码:
public void justDownloadWithoutUploading(){
final StorageReference img_dest;
img_dest = mStorageRef.child("images/" + currentUser.getUid().toString() + "/" + "20200203144042img.jpg");
FirebaseStorage storage = FirebaseStorage.getInstance();
final StorageReference storageRef = storage.getReference();
final StorageReference islandRef = storageRef.child("images/20200203144042img.jpg"); //gs://viproverselvfølgeligigjen.appspot.com/images/20200203144042img.jpg
final long ONE_MEGABYTE = 1024 * 1024;
islandRef.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
@Override
public void onSuccess(byte[] bytes) {
// Data for "images/island.jpg" is returns, use this as needed
downloadImage(img_dest); // ERROR: 2020-02-04 14:48:29.272 27487-27830/com.example.admin_panel E/StorageException: StorageException has occurred?
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle any errors
}
});
}
此方法将创建对特定图像的引用,然后最后调用“ public Task downloadImage”,将链接添加到参数中,但是什么也没有发生。.
完整错误:
2020-02-04 17:31:06.669 1020-1456/com.example.admin_panel E/StorageException: StorageException has occurred.
Object does not exist at location.
Code: -13010 HttpResult: 404
2020-02-04 17:31:06.671 1020-1456/com.example.admin_panel E/StorageException: Could not open resulting stream.
java.io.IOException: Could not open resulting stream.
at com.google.firebase.storage.StreamDownloadTask.createDownloadStream(com.google.firebase:firebase-storage@@16.0.4:143)
at com.google.firebase.storage.StreamDownloadTask.access$000(com.google.firebase:firebase-storage@@16.0.4:38)
at com.google.firebase.storage.StreamDownloadTask$1.call(com.google.firebase:firebase-storage@@16.0.4:165)
at com.google.firebase.storage.StreamDownloadTask$1.call(com.google.firebase:firebase-storage@@16.0.4:162)
at com.google.firebase.storage.StreamDownloadTask$StreamProgressWrapper.ensureStream(com.google.firebase:firebase-storage@@16.0.4:324)
at com.google.firebase.storage.StreamDownloadTask$StreamProgressWrapper.access$100(com.google.firebase:firebase-storage@@16.0.4:261)
at com.google.firebase.storage.StreamDownloadTask.run(com.google.firebase:firebase-storage@@16.0.4:173)
at com.google.firebase.storage.StorageTask.lambda$getRunnable$7(com.google.firebase:firebase-storage@@16.0.4:1106)
at com.google.firebase.storage.StorageTask$$Lambda$12.run(Unknown Source:2)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
这里有人可以帮助我吗?