当前位置: 首页 > 知识库问答 >
问题:

FireBase存储映像上载Android

虞华翰
2023-03-14

我创建了一个使用Firebase存储运行的应用。这个想法是,您从照片库中选择一张图片,然后将其上传到Firebase存储。与Firebase的连接似乎工作正常,我可以选择图像。当我按下提交按钮将其上传到Firebase时,问题就出现了。

当我点击它一次,什么也没发生。

当我点击它几次时,我得到一条消息“发生未知错误,请检查HTTP结果代码和内部异常”。。

我该怎么做,寻求建议。。

从舱单中:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>

从活动中:

public class PostActivity extends AppCompatActivity {

private static final int GALLERY_REQUEST = 2;
private Uri uri = null;
private ImageButton imageButton;
private EditText editName;
private EditText editDescription;
private StorageReference storageReference;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_post);
    //reference the two edittext Views, initialize them
    editName = (EditText) findViewById(R.id.editName);
    editDescription = (EditText) findViewById(R.id.editDescription);

    //add the reference to the storagereference, initialize it
    storageReference = FirebaseStorage.getInstance().getReference();
}

public void ImageButtonClicked (View view){
    Intent galleryintent = new Intent (Intent.ACTION_GET_CONTENT);
    galleryintent.setType("Image/*");  
    startActivityForResult(galleryintent, GALLERY_REQUEST);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK){

uri = data.getData();
imageButton = (ImageButton) findViewById(R.id.imageButton);
imageButton.setImageURI(uri);
    }
}

public void submitButtonClicked (View view){

    String titleValue = editName.getText().toString().trim();
    String titleDescription = editDescription.getText().toString().trim();

    if (!TextUtils.isEmpty(titleValue) && !TextUtils.isEmpty(titleDescription)){

        StorageReference filePath = storageReference.child("PostImage").child(uri.getLastPathSegment());

        filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

Uri downloadurl = taskSnapshot.getDownloadUrl();
Toast.makeText(PostActivity.this,"uploadcomplete",Toast.LENGTH_LONG).show();

            }
        });
filePath.putFile(uri).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {

       Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();

共有3个答案

单于亮
2023-03-14

要在Firebase上执行图像上传,请使用以下方法:

void uploadFile(String pathToFile, String fileName, String serverFolder, String contentType) {
    if (pathToFile != null && !pathToFile.isEmpty()) {

        File file = new File(pathToFile);
        if (file.exists()) {

            Uri uri = Uri.fromFile(new File(pathToFile));

            // Create a storage reference from our app
            mStorageRef = mFirebaseStorage.getReference();

            // Create a reference to "mountains.jpg"
            //StorageReference mountainsRef = storageRef.child(fileName);

            // Create a reference to 'images/mountains.jpg'
            StorageReference mountainImagesRef = mStorageRef.child(serverFolder+"/" + fileName);
            StorageMetadata metadata = null;
            if (contentType != null && !contentType.isEmpty()) {
                // Create file metadata including the content type
                metadata = new StorageMetadata.Builder()
                        .setContentType(contentType)
                        .build();
            }


            if (metadata != null) {
                uploadFileTask = mountainImagesRef.putFile(uri, metadata);
            } else {
                uploadFileTask = mountainImagesRef.putFile(uri);
            }

            uploadFileTask.addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    // Handle unsuccessful uploads
                    hideProgressDialog();
                    exception.printStackTrace();
                    Log.e(TAG,exception.getMessage());
                    if (firebaseUploadCallback!=null)
                    {
                        firebaseUploadCallback.onFirebaseUploadFailure(exception.getMessage());
                    }
                }
            });
            uploadFileTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
                    hideProgressDialog();
                    Uri downloadUrl = taskSnapshot.getDownloadUrl();
                    Log.e(TAG, "Upload is success "+ downloadUrl);
                    if (firebaseUploadCallback!=null)
                    {
                        firebaseUploadCallback.onFirebaseUploadSuccess("Upload is success "+ downloadUrl.toString(), downloadUrl.toString());
                    }
                }
            });
            // Observe state change events such as progress, pause, and resume
            uploadFileTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                    hideProgressDialog();
                    double progressPercent = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                    progressPercent = Double.parseDouble(FirebaseUtil.formatDecimal(progressPercent,2));
                    Log.e(TAG, "File Upload is " + progressPercent + "% done");
                    if (firebaseUploadCallback!=null)
                    {
                        firebaseUploadCallback.onFirebaseUploadProgress(progressPercent);
                    }
                }
            });
            uploadFileTask.addOnPausedListener(new OnPausedListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onPaused(UploadTask.TaskSnapshot taskSnapshot) {
                    hideProgressDialog();
                    Log.e(TAG, "Upload is paused");
                    if (firebaseUploadCallback!=null)
                    {
                        firebaseUploadCallback.onFirebaseUploadPaused("Upload is paused");
                    }
                }
            });
        }
        else
        {
            hideProgressDialog();
            Log.e(TAG, "Upload file does not exists");
            if (firebaseUploadCallback!=null)
            {
                firebaseUploadCallback.onFirebaseUploadFailure("Upload file does not exists");
            }
        }
    }else
    {
        hideProgressDialog();
        Log.e(TAG,"pathToFile cannot be null or empty");
        if (firebaseUploadCallback!=null)
        {
            firebaseUploadCallback.onFirebaseUploadFailure("pathToFile cannot be null or empty");
        }
    }
}

如下所示调用此方法:

public void uploadDummyPicture(String email, String imagePath){
    if (imagePath == null) {
        return;
    }
    if (!isValidEmail(email)) {
        return;
    }
    String serverFolder = "dummy_images/" + email; //path of your choice on firebase storage server
    String fileName = "DummyPhoto.png";
    uploadFile(imagePath, fileName, serverFolder, "image/png");
    showProgressDialog();
}

请确保在使用上述代码之前检查firebase存储规则,如下所述。如果规则要求firebase身份验证,则首先完成当前用户的firebase身份验证,然后开始上载文件。

我希望这个答案能解决你的问题。

昝涛
2023-03-14

我通过Rahul Chandrabhan的密码找到了答案。我所做的更改是删除以下方法的最后一部分:

StorageReference filePath = 
storageReference.child("PostImage").child(uri.getLastPathSegment());

TO 

StorageReference filePath = storageReference.child("PostImage");
公良飞尘
2023-03-14

尝试此方法将图像上载到firebase存储:

private void uploadMethod() {
        progressDialog();
        FirebaseStorage firebaseStorage = FirebaseStorage.getInstance();
        StorageReference storageReferenceProfilePic = firebaseStorage.getReference();
        StorageReference imageRef = storageReferenceProfilePic.child("Your Path" + "/" + "Image Name" + ".jpg");

        imageRef.putFile(imageUri)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        //if the upload is successful
                        //hiding the progress dialog
                        //and displaying a success toast
                        dismissDialog();
                        String profilePicUrl = taskSnapshot.getDownloadUrl().toString();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        //if the upload is not successful
                        //hiding the progress dialog
                        dismissDialog();
                        //and displaying error message
                        Toast.makeText(getActivity(), exception.getCause().getLocalizedMessage(), Toast.LENGTH_LONG).show();
                    }
                })
                .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                        //calculating progress percentage
//                        double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
//                        //displaying percentage in progress dialog
//                        progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
                    }
                });

    }
 类似资料:
  • 我正在使用以下方法来保存信息。 我已经删除了一些用于访问数据库的代码行。 这是日志猫的描述。 E/StorageException:已发生StorageException。发生未知错误,请检查HTTP结果代码和内部异常以获取服务器响应。代码:-13000 HttpResult:0 E/AndroidRuntime:FATAL EXCEPTION:Firebase Storage-Upload-1

  • 我正在制作这个应用程序,用户可以有一张个人资料图片(但只有一张图片每人)。我得到了所有的设置,但当图片是2MB+时,它需要一些时间来加载,实际上我只需要图片是50KB左右(只有图片的小显示,最大40像素)。我做了一些代码将图像直接放入实时数据库(转换为画布并使它们成为一个7KB的base64字符串)。但是,这并不是真的干净,最好使用Firebase存储。 自从新的更新3.3.0以来,您可以使用pu

  • 我试图在Firebase存储中使用Firebase上传图像,但文件不能完全上传。它只显示图像的大小9字节,下载时无法预览。 这是我使用的代码:- 我使用的反应本地图像作物选择器。我使用Firebase,但不是反应本机Firebase。请帮助!

  • Firebase存储图像三分之二天未显示。我有一些发布的应用程序,在这些应用程序里面有一些图片显示从Firebase存储,现在突然它不显示/查看。我还从浏览器>Firebase Console>Storage检查了那些图像,但它没有显示图像预览,并且显示:“错误加载预览”。但我的Firebase Firestore数据显示没有任何错误。我查了储存配额,没有问题。我的火力点计划是“燃烧”,随走随付。

  • 错误是 我尝试过使用bucket权限,并尝试在google cloud storage中添加权限(如本文所述),但没有任何帮助。任何想法都将不胜感激!

  • 我想在上传到Firebase存储之前调整图像的大小。 我的问题是:FireBase在其Uri上上传图像。我从图库意图中获取图像,并将其放在上,然后像这样调整其大小: firebase根据Uri像这样上传它(如果有其他上传文件的方法,它将非常有用!): 有没有办法获取