简体   繁体   中英

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?

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

I pretty much doubt this points to existing file on your device .

EDIT

But if I change filepath to content://media/external/images/media/12

This is NOT file path. Using content:// Uri, requires using a ContentResolver and methods like openInputStream() and openOutputStream() .

            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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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