我很难将图像从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());
对于此问题的任何帮助,我们将不胜感激。
答案 0 :(得分:0)
经过大量研究,我发现到目前为止我认为是最好的解决方案。基本上,我需要通过转换为位图将试图从外部存储发送到内部的照片复制到内部。完整解决方案如下。请让我知道是否有更好的人。
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());