android - 在 Android 中使用 Azure 存储获取上传进度

标签 android azure azure-storage progress

我正在 Android 应用程序中上传文件。代码非常简单:

    private boolean UploadFile(String fileLocation) {
        try {

            if (TextUtils.isEmpty(fileLocation)) {
                return false;
            }

            File fSrc = new File(fileLocation);

            if (!fSrc.exists()) {
                return false;
            }

            boolean bReturn = AzureManager.init(this);
            if (!bReturn) {
                return false;
            }

            String blobName = fSrc.getName();

            InputStream in = new BufferedInputStream(new FileInputStream(fSrc));
            CloudBlobContainer container = AzureManager.getCloudBlobClient().getContainerReference(AzureManager.getContainerName());
            CloudBlockBlob blob = container.getBlockBlobReference(blobName);
            blob.upload(in, fSrc.length());

            in.close();
            return true;
        } catch (Exception e) {
            //handle exception
        }
        return false;
    }

当我从 Azure 下载时,CloudBlockBlob 有一个下载监听器:

blob.setDownloadListener(eventListener);

但是我如何在上传时跟踪进度?

最佳答案

我也在寻找在 Java 或 Android 中执行此操作的方法。但是,如果您想按照自己的方式制作,而不更改服务器上的任何内容,您可以将其制作类似于 this answer 。答案是在 C# 中,因此您需要为 Java 库找到类似的方法并相应地更新它。

如果您不想继续该答案,也可以从此处引用相同的代码。

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials("accountname", "accountkey"), true);
        static void Main(string[] args)
        {
            CloudBlobClient myBlobClient = storageAccount.CreateCloudBlobClient();
            myBlobClient.SingleBlobUploadThresholdInBytes = 1024 * 1024;
            CloudBlobContainer container = myBlobClient.GetContainerReference("adokontajnerneki");
            //container.CreateIfNotExists();
            CloudBlockBlob myBlob = container.GetBlockBlobReference("cfx.zip");
            var blockSize = 256 * 1024;
            myBlob.StreamWriteSizeInBytes = blockSize;
            var fileName = @"D:\cfx.zip";
            long bytesToUpload = (new FileInfo(fileName)).Length;
            long fileSize = bytesToUpload;

            if (bytesToUpload < blockSize)
            {
                CancellationToken ca = new CancellationToken();
                var ado = myBlob.UploadFromFileAsync(fileName, FileMode.Open, ca);
                Console.WriteLine(ado.Status); //Does Not Help Much
                ado.ContinueWith(t =>
                {
                    Console.WriteLine("Status = " + t.Status);
                    Console.WriteLine("It is over"); //this is working OK
                });
            }
            else
            {
                List<string> blockIds = new List<string>();
                int index = 1;
                long startPosition = 0;
                long bytesUploaded = 0;
                do
                {
                    var bytesToRead = Math.Min(blockSize, bytesToUpload);
                    var blobContents = new byte[bytesToRead];
                    using (FileStream fs = new FileStream(fileName, FileMode.Open))
                    {
                        fs.Position = startPosition;
                        fs.Read(blobContents, 0, (int)bytesToRead);
                    }
                    ManualResetEvent mre = new ManualResetEvent(false);
                    var blockId = Convert.ToBase64String(Encoding.UTF8.GetBytes(index.ToString("d6")));
                    Console.WriteLine("Now uploading block # " + index.ToString("d6"));
                    blockIds.Add(blockId);
                    var ado = myBlob.PutBlockAsync(blockId, new MemoryStream(blobContents), null);
                    ado.ContinueWith(t =>
                    {
                        bytesUploaded += bytesToRead;
                        bytesToUpload -= bytesToRead;
                        startPosition += bytesToRead;
                        index++;
                        double percentComplete = (double)bytesUploaded / (double)fileSize;
                        Console.WriteLine("Percent complete = " + percentComplete.ToString("P"));
                        mre.Set();
                    });
                    mre.WaitOne();
                }
                while (bytesToUpload > 0);
                Console.WriteLine("Now committing block list");
                var pbl = myBlob.PutBlockListAsync(blockIds);
                pbl.ContinueWith(t =>
                {
                    Console.WriteLine("Blob uploaded completely.");
                });
            }
            Console.ReadKey();
        }
    }
}

关于android - 在 Android 中使用 Azure 存储获取上传进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23696914/

相关文章:

azure - 从操作系统获取环境变量

c# - 尝试连接到 SQL Azure 数据库时出现异常

android - 标签主机中不显示图像

android - 如何使用 Firebase 启用安全的用户数据访问而不需要用户登录

azure - 集成了 azurite 的 Visual studio 2022 (v3.14.1) 在创建本地 blob 容器时给出错误消息 InvalidHeaderValue

azure - Microsoft Azure 上的异地冗余存储如何收费?

azure存储公共(public)网站通过azure域 Controller 控制访问

android - Appcompat 工具栏不显示任何图标

android - CardView 类似于 Google Play 使用的那些

azure - 逻辑应用 blob 触发器未在子文件夹上触发