gpt4 book ai didi

java - 从 Android 示例上传 Azure 存储 block Blob

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:10:12 25 4
gpt4 key购买 nike

我正在使用 Android 应用程序中的以下代码将 Blob 上传到 Azure Blob 存储。注意:下面的 sasUrl 参数是从我的网络服务获取的签名 url:

    // upload file to azure blob storage
private static Boolean upload(String sasUrl, String filePath, String mimeType) {
try {
// Get the file data
File file = new File(filePath);
if (!file.exists()) {
return false;
}

String absoluteFilePath = file.getAbsolutePath();

FileInputStream fis = new FileInputStream(absoluteFilePath);
int bytesRead = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
while ((bytesRead = fis.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
fis.close();
byte[] bytes = bos.toByteArray();
// Post our image data (byte array) to the server
URL url = new URL(sasUrl.replace("\"", ""));
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setConnectTimeout(15000);
urlConnection.setReadTimeout(15000);
urlConnection.setRequestMethod("PUT");
urlConnection.addRequestProperty("Content-Type", mimeType);
urlConnection.setRequestProperty("Content-Length", "" + bytes.length);
urlConnection.setRequestProperty("x-ms-blob-type", "BlockBlob");
// Write file data to server
DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
wr.write(bytes);
wr.flush();
wr.close();
int response = urlConnection.getResponseCode();
if (response == 201 && urlConnection.getResponseMessage().equals("Created")) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}

该代码对于小 blob 运行良好,但是当 blob 达到特定大小时(取决于我正在测试的手机),我开始出现内存不足异常。我想拆分 blob 并将它们上传到 block 中。但是,我在网上找到的所有示例都是基于 C# 的,并且使用的是 Storage Client 库。我正在寻找使用 Azure Storage Rest API 以 block 的形式上传 blob 的 Java/Android 示例。

最佳答案

发布了一个 Azure Storage Android 库 here .基本blob storage example在示例文件夹中。您可能想要使用的方法是 blob 类中的 uploadFromFile。默认情况下,如果大小小于 64MB,这将尝试将 blob 放入单个 put 中,否则以 4MB block 发送 blob。如果您想减少 64MB 的限制,您可以在 CloudBlobClient 的 BlobRequestOptions 对象上设置 singleBlobPutThresholdInBytes 属性(这将影响所有请求)或传递给 uploadFromFile 方法(仅影响该请求)。存储库包括许多方便的功能,例如自动重试和跨区 block 放置请求的最大执行超时,这些都是可配置的。

如果您仍想使用更手动的方法,PutBlock 和 Put Block List API 引用是 here并提供通用的跨语言文档。这些在 Azure 存储 Android 库的 CloudBlockBlob 类中有很好的包装器,称为 uploadBlock 和 commitBlockList,它们可以为您节省大量手动请求构建时间,并可以提供上述一些便利。

关于java - 从 Android 示例上传 Azure 存储 block Blob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24424543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com