【问题标题】:How can we `Download media` from firebase url我们如何从firebase url“下载媒体”
【发布时间】:2018-02-27 22:15:03
【问题描述】:
  • 我是 Android 新手,不知道如何从以下位置下载 media firebase
  • uploadFile 方法中,我在FirebaseStorage 中上传媒体,并在获得成功响应后downloadUrl = taskSnapshot.getDownloadUrl() 发送到FirebaseDatabase
  • 我也收到了url,但无法从url 获得download 媒体

   private void uploadFile(Uri uri) {
    StorageReference uploadStorageReference = mStorageReferenceMedia.child(uri.getLastPathSegment());
    final UploadTask uploadTask = uploadStorageReference.putFile(uri);
    showHorizontalProgressDialog("Uploading", "Please wait...");
    uploadTask
            .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    hideProgressDialog();
                    downloadUrl = taskSnapshot.getDownloadUrl();
                    Log.e("MainActivity"+"241>>>>", downloadUrl.toString());
                    Toast.makeText(ActivityChatView.this, "ulr>>"+downloadUrl, Toast.LENGTH_SHORT).show();
                    sendURL();

                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    exception.printStackTrace();
                    // Handle unsuccessful uploads
                    hideProgressDialog();
                }
            })
            .addOnProgressListener(ActivityChatView.this, new OnProgressListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                    int progress = (int) (100 * (float) taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
                    Log.e("Progress>>", progress + "");
                    updateProgress(progress);
                }
            });
}


public class DownloadTask {

    private static final String TAG = "Download Task";
    private Context context;
    private Button buttonText;
    private String downloadUrl = "", downloadFileName = "";

    public DownloadTask(Context context, String downloadUrl) {
        this.context = context;
        this.buttonText = buttonText;
        this.downloadUrl = downloadUrl;

        downloadFileName = downloadUrl.replace("", "");//Create file name by picking download file name from URL
        Log.e(TAG, downloadFileName);

        //Start Downloading Task
        new DownloadingTask().execute();
    }

    private class DownloadingTask extends AsyncTask<Void, Void, Void> {

        File apkStorage = null;
        File outputFile = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(Void result) {
            try {
                if (outputFile != null) {
                    buttonText.setEnabled(true);
                    Log.e("57","download"+"completed");
                } else {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Log.e("62","download again");
                        }
                    }, 3000);

                    Log.e(TAG, "Download Failed");

                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("72,","download failed");
                //Change button text if exception occurs
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("80","download again");
                    }
                }, 3000);
                Log.e(TAG, "Download Failed with Exception - " + e.getLocalizedMessage());

            }


            super.onPostExecute(result);
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            try {
                URL url = new URL(downloadUrl);//Create Download URl
                HttpURLConnection c = (HttpURLConnection) url.openConnection();//Open Url Connection
                c.setRequestMethod("GET");//Set Request Method to "GET" since we are grtting data
                c.connect();//connect the URL Connection

                //If Connection response is not OK then show Logs
                if (c.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    Log.e(TAG, "Server returned HTTP " + c.getResponseCode()
                            + " " + c.getResponseMessage());

                }


                //Get File if SD card is present
                if (new CheckForSDCard().isSDCardPresent()) {

                    apkStorage = new File(Environment.getExternalStorageDirectory() + "/"
                                    + "downloadDirectory");
                } else
                    Toast.makeText(context, "Oops!! There is no SD Card.", Toast.LENGTH_SHORT).show();

                //If File is not present create directory
                if (!apkStorage.exists()) {
                    apkStorage.mkdir();
                    Log.e(TAG, "Directory Created.");
                }

                outputFile = new File(apkStorage, downloadFileName);//Create Output file in Main File

                //Create New File if not present
                if (!outputFile.exists()) {
                    outputFile.createNewFile();
                    Log.e(TAG, "File Created");
                }

                FileOutputStream fos = new FileOutputStream(outputFile);//Get OutputStream for NewFile Location

                InputStream is = c.getInputStream();//Get InputStream for connection

                byte[] buffer = new byte[1024];//Set buffer type
                int len1 = 0;//init length
                while ((len1 = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len1);//Write new file
                }

                //Close all connection after doing task
                fos.close();
                is.close();

            } catch (Exception e) {

                //Read exception if something went wrong
                e.printStackTrace();
                outputFile = null;
                Log.e(TAG, "Download Error Exception " + e.getMessage());
            }

            return null;
        }
    }
}

【问题讨论】:

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


    【解决方案1】:

    您应该使用 StorageReferencedownload file from Firebase Storage

    从 URL 下载文件

    // Create a storage reference from our app
    StorageReference storageRef = storage.getReference();
    
    // Create a reference to a file from a Google Cloud Storage URI
    StorageReference gsReference = 
        storage.getReferenceFromUrl("gs://bucket/images/stars.jpg");
    
    //Download file in Memory
    StorageReference islandRef = storageRef.child("images/island.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
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            // Handle any errors
        }
    });
    

    阅读this了解更多详情和下载文件的其他选项。

    阅读this 上传文件。

    【讨论】:

      【解决方案2】:

      比起 AsyncTask 和 HttpURLConnection 的组合,我会推荐 DownloadManager,因为它是正确的做法,它可以从文档中的中断处继续下载

      下载管理器是处理长时间运行的系统服务 HTTP 下载。客户端可能会请求将 URI 下载到 特定的目标文件。下载管理器将执行 在后台下载,负责 HTTP 交互和 在失败或跨连接更改后重试下载和 系统重启。

      请参考example。 为了进一步帮助您进行调试,请考虑这个

      1) 请通过验证确保该 url 实际上传到数据库中,并在下载过程中根据您的需要提供一个带扩展名的正确名称。
      2) 物理打开文件位置以查看文件是否至少已创建,并为文件使用正确的文件扩展名,如 .mp3 或 .txt。
      3)您取决于从 db 获得的名称是否适合扩展,

      【讨论】:

        猜你喜欢
        • 2023-03-25
        • 2015-07-02
        • 1970-01-01
        • 2016-09-02
        • 2016-11-04
        • 1970-01-01
        • 1970-01-01
        • 2021-08-18
        • 2021-09-15
        相关资源
        最近更新 更多