[英]Azure storage block blob upload from android example
我正在使用以下来自Android应用程序的代码将Blob上传到Azure Blob存储。 注意:以下sasUrl
参数是从我的Web服务获取的签名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拆分并按块上传。 但是,我在网上找到的所有示例都是基于C#的,并且都在使用Storage Client库。 我正在寻找一个Java / Android示例,该示例使用Azure Storage Rest API上载块中的Blob。
这里发布了一个Azure存储Android库。 示例文件夹中有一个基本的Blob存储示例 。 您可能要使用的方法是blob类中的uploadFromFile。 如果大小小于64MB,默认情况下将尝试将blob放入一个put中,否则将以4MB的块发送blob。 如果您希望减少64MB的限制,则可以在CloudBlobClient的BlobRequestOptions对象上设置singleBlobPutThresholdInBytes属性(这会影响所有请求),也可以将其设置为传递给uploadFromFile方法(仅影响该请求)。 存储库包括许多便利的功能,例如跨块放置请求的自动重试和最大执行超时,这些都是可配置的。
如果你仍想使用更多的手工方法,在PutBlock和放置块列表API引用在这里 ,并提供通用的,跨语言的文档。 它们在Azure存储Android库的CloudBlockBlob类(称为uploadBlock和commitBlockList)中具有很好的包装,这可以为您节省大量的手动请求构建时间,并可以提供一些上述便利。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.