繁体   English   中英

如何从Android上将图像blob上传到Azure

[英]How to upload image blobs to Azure from Android

我很难将图像从Android设备上传到我的Azure云存储帐户。

下面是我已经开始工作的代码。 但是,用户选择的图像返回一个URI,我无法得到一个解决方案,它涉及将uri转换为文件路径(“工作”示例中的硬编码。我在线阅读文件路径不再可接受了,所以我试图将照片转换为位图,并尝试使用涉及getContextResolver()的多个解决方案。但每次我尝试不同的策略,找不到文件或我得到空指针异常。

//Code that works
final String filePath = "storage/emulated/0/DCIM/Camera/IMG_20190328_141613.jpg";
CloudBlockBlob blob = container.getBlockBlobReference(blobName);
File source = new File(filePath);
blob.upload(new FileInputStream(source), source.length());
//Alternative 1 that doesnt work
CloudBlockBlob blob = container.getBlockBlobReference(blobName);
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImageUri,projection,null,null,null);
cursor.moveToFirst();
int colIndex = cursor.getColumnIndex(projection[0]);
String filePath = cursor.getString(colIndex);
cursor.close();
File source = new File(filePath);
blob.upload(new FileInputStream(source), source.length());

非常感谢任何有关此问题的帮助。

经过一番研究,我发现到目前为止我认为是最好的解决方案。 基本上我需要通过转换为位图来复制我试图从外部存储器发送到内部的照片。 完整解决方案如下 如果有人有更好的,请告诉我。

String connectionString = "{account key}";

CloudStorageAccount storageAccount = CloudStorageAccount.parse(connectionString);

// Create the blob client
CloudBlobClient blobClient = storageAccount.createCloudBlobClient();

// Get a reference to a container
// The container name must be lower case
CloudBlobContainer container = blobClient.getContainerReference({bucketName});

//Create new file
File f = new File(getApplicationContext().getCacheDir(), blobName);
f.createNewFile();

//Create byte array stream
ByteArrayOutputStream bos = new ByteArrayOutputStream();

/*bitmap is loaded in the onCreate method (not shown in this block) Quality is 0-100 where 100 is the best*/
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);

byte[] bitmapdata = bos.toByteArray();

//write bitmap to file, flush and close.
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();

//upload bitmap from local directory
final String filePath = getApplicationContext().getCacheDir() + blobName;
CloudBlockBlob blob = container.getBlockBlobReference(blobName);
File source = new File(f.getAbsolutePath());
blob.upload(new FileInputStream(source), source.length());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM