You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android SDK缺失Azure Mobile Apps FileSync支持,求Blob存储上传方案

实现Android端通过Azure Mobile App上传文件到Blob存储

我帮你梳理下可行的实现方案——因为官方Azure Mobile Apps Android SDK确实没有直接封装文件上传到Blob的功能,所以我们需要结合后端自定义API和Azure Storage SDK来完成:

1. 先在Azure Mobile App后端创建自定义API生成SAS令牌

直接在客户端暴露存储账户密钥存在安全风险,所以我们需要通过后端生成共享访问签名(SAS)令牌,客户端凭借这个令牌安全上传文件。

假设你的后端是.NET技术栈(和你提到的博客示例一致),可以创建一个自定义API控制器,代码大致如下:

using Microsoft.Azure.Mobile.Server;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System.Web.Http;

public class BlobUploadController : ApiController
{
    // 从Mobile App应用设置中读取Blob存储连接字符串
    private readonly string storageConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["你的Blob存储连接字符串名称"].ConnectionString;
    private readonly string containerName = "your-container-name"; // 替换为你的Blob容器名

    [HttpGet]
    public IHttpActionResult GetSasToken()
    {
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer container = blobClient.GetContainerReference(containerName);

        // 配置SAS令牌的权限与有效期(示例设置为1小时)
        SharedAccessBlobPolicy sasPolicy = new SharedAccessBlobPolicy
        {
            Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Create,
            SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1)
        };

        // 生成SAS令牌并返回容器地址
        string sasToken = container.GetSharedAccessSignature(sasPolicy);
        return Ok(new { ContainerUri = container.Uri.AbsoluteUri, SasToken = sasToken });
    }
}

部署这个API后,记住它的访问路径(比如https://你的mobile-app-url/api/blobupload)。

2. Android端实现上传逻辑

首先在Android项目的build.gradle中添加Azure Storage SDK依赖:

dependencies {
    implementation 'com.microsoft.azure.android:azure-storage-android:8.0.0'
    // 确保已添加Azure Mobile Apps SDK依赖
    implementation 'com.microsoft.azure:azure-mobile-apps-android:4.4.0'
}

然后编写代码,分两步完成上传:调用自定义API获取SAS令牌,再利用令牌上传文件:

import com.microsoft.azure.storage.blob.CloudBlobContainer;
import com.microsoft.azure.storage.blob.CloudBlockBlob;
import com.microsoft.azure.storage.blob.StorageUri;
import com.microsoft.azure.storage.blob.StorageCredentialsSharedAccessSignature;
import com.microsoft.azure.mobile.client.AzureMobileClient;
import com.microsoft.azure.mobile.client.http.ServiceFilterResponse;
import com.microsoft.azure.mobile.client.http.HttpCallback;
import org.json.JSONObject;

// 初始化Azure Mobile Client(你应该已经完成这部分配置)
AzureMobileClient mobileClient = new AzureMobileClient(getApplicationContext(), "你的Mobile App URL", null);

// 第一步:调用自定义API获取SAS令牌
mobileClient.invokeApi("blobupload", null, "GET", null, new HttpCallback() {
    @Override
    public void onSuccess(JSONObject response, ServiceFilterResponse rawResponse) {
        try {
            String containerUri = response.getString("ContainerUri");
            String sasToken = response.getString("SasToken");
            
            // 第二步:使用SAS令牌上传文件
            uploadFileToBlob(containerUri, sasToken, "/path/to/your/local/file.jpg", "uploaded-file.jpg");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Exception exception, ServiceFilterResponse rawResponse) {
        exception.printStackTrace();
        // 处理API调用失败的逻辑
    }
});

// 封装文件上传方法
private void uploadFileToBlob(String containerUri, String sasToken, String localFilePath, String blobName) {
    try {
        // 创建存储凭证
        StorageCredentialsSharedAccessSignature credentials = new StorageCredentialsSharedAccessSignature(sasToken);
        CloudBlobContainer container = new CloudBlobContainer(new StorageUri(containerUri), credentials);
        
        // 获取目标Blob引用
        CloudBlockBlob blob = container.getBlockBlobReference(blobName);
        
        // 上传本地文件
        blob.uploadFromFile(localFilePath);
        
        // 上传成功后的UI更新逻辑
        runOnUiThread(() -> {
            // 比如显示上传成功提示
        });
    } catch (Exception e) {
        e.printStackTrace();
        // 处理上传失败的逻辑
    }
}

关键注意事项

  • 确保你的Blob容器权限设置合理:如果是私有容器,必须依赖SAS令牌访问;如果是公共容器,虽然可以直接上传,但安全性远不如SAS方式。
  • 后端可以根据业务需求调整SAS令牌的权限和有效期,比如仅授予写入权限、缩短有效期,降低令牌泄露的风险。
  • Android端需要申请文件读取权限,在AndroidManifest.xml中添加:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Android 10及以上版本还需要适配分区存储规则。

内容的提问来源于stack exchange,提问作者Arun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:57:20