Azure blob storage from Android

I try to upload image to Azure Blob storage from android. I can do it from Java by this way

 CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);

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

        CloudBlobContainer container = blobClient.getContainerReference("mycontainer");

        final String filePath = "C:\Users\icon.jpg";

        CloudBlockBlob blob = container.getBlockBlobReference("1.jpg");
        File source = new File(filePath);
        blob.upload(new FileInputStream(source), source.length());

But if I change filepath to “content://media/external/images/media/12” this, in android I have FileNotFoundException. How can I upload images from android?

Answer

            CloudBlockBlob blob = container.getBlockBlobReference(UserInfo.username + ".jpg");
            BlobOutputStream blobOutputStream = blob.openOutputStream();
            ContentResolver cr = context.getContentResolver();
            InputStream s = cr.openInputStream(uri);
            byte[] arr = convertInputStreamToByteArray(s);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(arr);
            int next = inputStream.read();
            while (next != -1) {
                blobOutputStream.write(next);
                next = inputStream.read();
            }
            blobOutputStream.close();

Convert the stream is like that

 public byte[] convertInputStreamToByteArray(InputStream inputStream)
    {
        byte[] bytes= null;

        try
        {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            byte data[] = new byte[1024];
            int count;

            while ((count = inputStream.read(data)) != -1)
            {
                bos.write(data, 0, count);
            }

            bos.flush();
            bos.close();
            inputStream.close();

            bytes = bos.toByteArray();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return bytes;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *