Android-Upload image files to Azure Blob Storage in Java

Self-introduction

I'm Fumiya Kume, a second year student at Daido University. I'm playing with Xamarin.

What is Azure Blob Storage?

Azure Blob Storage offers exabytes of capacity and extremely high scalability, making it easy and cost-effective to place hundreds to billions of objects in the hot or cool tier, depending on how often you need to access your data. Can be stored. You can store all kinds of unstructured data, including images, videos, audio and documents.

Quoted from https://azure.microsoft.com/ja-jp/services/storage/blobs/

It's accurate, but it's difficult to read, so I'll break it down a bit. Simply put, it's a storage that can store any file, whether it's an image, text, or video.

If you use it to save data posted by users on SNS etc., it will be easier to understand if you can imagine it.

The cost of saving files and transferring from the cloud is

--File storage: Up to 1TB is ¥ 2.45 / GB, --Transfer from the cloud: ¥ 0.37 per 100,000 times

It's like that. I think it's cheap.

Reference: Azure Storage Pricing

What to do this time

Upload images from Android to Azure Blob Storage.

Preparation

--Microsoft Azure account with subscription enabled --Android Studio (I used 2.3)

What i did

1. Create an Android project

I think it's okay if you choose the Empty Activity template.

studio64_2017-03-31_23-08-29[1].png

2. Place one button

// Since it is a basic part, the code is omitted

The id should be ** button **.

3. Prepare on the Azure side

Access the Azure portal

chrome_2017-03-31_23-11-25[1].png

Create Blob Storage

Click the ** + ** button in the upper right and enter ** Blob ** in the search box that appears to suggest Azure Blob Storage. Click on it.

chrome_2017-03-31_23-12-23[1].png

Continue setting up Azure Blob Storage

Give it a unique name for all users in Azure. Give the resource group a unique name for each individual user. Subscriptions cannot be created with subscriptions provided by Imagine, so you can also participate in MSP-sponsored events etc. ** Azure Pass ** Please use etc.

Finally, click ** Pin to Dashboard ** and click Finish to complete the setting.

chrome_2017-03-31_23-16-07[1].png

Azure Blob Storage created

I think the following screen will open.

chrome_2017-03-31_23-21-54[1].png

Let's open the ** Blob ** part of the service category

chrome_2017-03-31_23-35-49[1].png

chrome_2017-04-01_00-05-23[1].png

You may have received a message that the container has not been created yet.

Container ... what is it like?

Now let's take a look at how Azure Blob Storage works.

blob1[1].png

Quoted from Using Azure Blob Storage with .NET

It may be hard to understand at first glance, so why not replace it with the computer terminology you are used to?

Account = USB memory Container = Folder in USB memory BLOB = Image collection and video collection placed in the folder

I feel like you understand, right?

Create a container for Azure Blobs

Create a container from the button on the upper left.

chrome_2017-04-01_00-38-25[1].png

One thing to keep in mind when naming Azure Blob Storage containers, they must be all lowercase

Also, the access type should be Blob

Azure is now ready.

4. Creating logic to connect to Azure Blob Storage on the Android side

Open ** MainActivity.java ** on Android. Then enter the code below


//import omitted

public class MainActivity extends AppCompatActivity {

    public Button Button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button = (Button) findViewById(R.id.button);
        Button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //If you execute heavy processing using the network in the UI thread, it will cause trouble, so execute it in another thread
                AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
                    @Override
                    protected Void doInBackground(Void... params) {
                        //String for connecting with Azure Blob Storage, Cho important. It's as important as the password for the Root account.
                        String storageConnectionString = "Connection String";
                        //Get the path to DCIM
                        File dir = new File(Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DCIM);
                        //Set the path to the image file on DCIM
                        File file = new File(dir.getAbsolutePath() + "/image.jpeg ");
                        //Log output to check if the path to the correct image is taken
                        Log.d("The one who displays the image", file.getPath());
                        try {
                            //Start connecting to Azure Storage Account
                            CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);

                            //Get a client to connect to a blob in your Azure Storage Account
                            CloudBlobClient blobClient = storageAccount.createCloudBlobClient();

                            //Get the blob container, specify the container as a string
                            CloudBlobContainer container = blobClient.getContainerReference("mspjp");

                            //The character string passed in the argument of getBlockBlobReference becomes the file name saved in Blob.
                            //If a file with the same name already exists, it will be overwritten
                            CloudBlockBlob blob = container.getBlockBlobReference("myimage.jpg ");
                            //Exit the function if the file does not exist
                            if (!file.exists()) return null;
                            //Upload to Azure Blob Storage
                            blob.upload(new java.io.FileInputStream(file), filelength());
                        } catch (Exception e) {
                            //Spits a stack trace for analysis if an error occurs
                            e.printStackTrace();
                        }
                        return null;
                    }
                };

                try {
                    //Run in a separate thread
                    task.execute();
                } catch (Exception e) {
                    Handler handler = new Handler();
                    handler.post(new Runnable() {
                        //I want to display an error message on toast when an error occurs,
                        //I'm running in the UI thread because I can't see the toast unless it's in the UI thread
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "Faild: Upload blob storage", Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        });

    }
}

5. Placement of images for upload

Connect Android to your PC, open the external storage of Android, and put the image file ** image.jpeg ** in the folder ** DCIM ** in it.

6. Setting storageConnectionString

The storageConnectionString is different for each user (Storage Account), so let's get it now.

First, open the Azure Blob Storage screen you created earlier.

Click on the part labeled Access Key

chrome_2017-04-01_01-03-35[1].png

Rewrite the code to copy the connection string of ** key1 ** and assign it to ** storageConnectionString **

chrome_2017-04-01_01-04-31[1].png

Run

Now that the coding is complete, try running it.

After running, open the Azure Blob Storage container and you'll see the image uploaded.

chrome_2017-04-01_01-08-23[1].png

Impressions

--Java fun ――Since Azure has all the documents, I felt that it was easy to solve even if I didn't understand.

Reference material

Recommended Posts

Android-Upload image files to Azure Blob Storage in Java
Operate Azure Blob Storage in Java (SAS token, file operation)
Java-How to compare image files in binary
Convert SVG files to PNG files in Java
Java upload and download notes to Azure storage
Azure functions in java
How to input / output IBM mainframe files in Java?
Read binary files in Java 1
Create Azure Functions in Java
Read binary files in Java 2
Append text to BlobItem in Azure BlobStorage SDK Java V8
Easily read text files in Java (Java 11 & Java 7)
Multithreaded to fit in [Java] template
How to disassemble Java class files
Run Java application in Azure Batch
How to learn JAVA in 7 days
Log output to file in Java
How to decompile java class files
How to use classes in Java?
How to name variables in Java
Try to implement Yubaba in Java
How to concatenate strings in java
How to implement Kalman filter in Java
Try to solve Project Euler in Java
Easy to make Slack Bot in Java
Java reference to understand in the figure
Try to implement n-ary addition in Java
* Android * Saving / loading files to internal storage
[Java] How to output and write files!
Change List <Optional <T >> to Optional <List <T >> in Java
How to implement coding conventions in Java
How to embed Janus Graph in Java
Play RAW, WAV, MP3 files in Java
Add Document to Azure Search Service (Java)
How to get the date in java
Add footnotes to Word documents in Java
Creating Java Web Applications to Azure Web Apps
[Java Bronze] 5 problems to keep in mind
Sample to unzip gz file in Java
Java to C and C to Java in Android Studio
Reading and writing gzip files in Java
Steps to register Java files on GitHub
Add SameSite attribute to cookie in Java
Try adding text to an image in Scala using the Java standard library
How to implement image posting function using Active Storage in Ruby on Rails
Upsert from Java SDK to Azure Cosmos DB
Two ways to start a thread in Java + @
[Rails] Various ways to write in seed files
I want to send an email in Java.
Deploy Java web app to Azure with maven
CORBA seems to be removed in Java SE 11. .. ..
Code to escape a JSON string in Java
Try to create a bulletin board in Java
I tried to implement deep learning in Java
How to get Class from Element in Java
I wanted to make (a == 1 && a == 2 && a == 3) true in Java
How to update pre-built files in docker container
How to hide null fields in response in Java
Library "OSHI" to get system information in Java
I tried to output multiplication table in Java
[Java] How to substitute Model Mapper in Jackson