4

I am using the following code from an android application to upload a blob to Azure Blob Storage. Note: the sasUrl parameter below is a signed url acquired from my web service :

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

The code is working fine for small blobs but when a blob reaches a certain size depending on the phone I am testing with, I start to get out of memory exceptions. I would like to split the blobs and upload them in blocks. However, all the examples I find on the web are C# based and are using the Storage Client library. I am looking for a Java/Android example that uploads a blob in blocks using the Azure Storage Rest API.

1 Answer 1

10

There is an Azure Storage Android library published here. A basic blob storage example is in the samples folder. The method you’d probably like to use is uploadFromFile in the blob class. This will, by default attempt to put the blob in a single put if the size is less than 64MB and otherwise send the blob in 4MB blocks. If you’d like to reduce the 64MB limit, you can set the singleBlobPutThresholdInBytes property on the BlobRequestOptions object of either the CloudBlobClient (which will affect all requests) or passed to the uploadFromFile method (to affect only that request). The storage library includes many convenient features such as automated retries and maximum execution timeout across the block put requests which are all configurable.

If you’d still like to use a more manual approach, the PutBlock and Put Block List API references are here and provide generic, cross-language documentation. These have nice wrappers in the CloudBlockBlob class of the Azure Storage Android library called uploadBlock and commitBlockList which may save you a lot of time in manual request construction and can provide some of the aforementioned conveniences.

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks! I can't believe I didn't come across this library and somehow kept returning to the Mobile Services Client library. One thing though, most methods in the CloudBlockBlob class expect me to provide my storage account name and key. I am not sure if distributing these with my app is a good idea.
Definitely don't distribute account/key! Use either a public access policy or a shared access signature. More info on SAS is here and here. Public access is discussed in more detail here. The appropriate API's to look at are container uploadPermissions, blob/container generateSharedAccessSignature, and the BlobContainerPermissions and SharedAccessBlobPolicy classes.
Very Helpful .but i cant find any function associated with to notify the upload or download completion ,how can i do that ?
@EmilyGerner, Thanks for the link. Is the project on Github still maintained? I see the last commit was 3 years ago. Can we still use this library? Thanks for your time.
I guess the newest available for java/android is this:learn.microsoft.com/en-us/java/api/overview/azure/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.