Skip to content
Advertisement

How to handle blob store url when receive from API

I have an API URL (e.g.: localhost:8080/api/blobs/download/{item-id}). The API itself will return the URL of that item in the Blob Store (for example, https://myaccount.blob.core.windows.net/mycontainer/myitem). Now I have a task that requires user to copy and paste the API URL into the browser, and expect it to view/download the item.

The question is how Java can support user browse the Blob Store URL without the help of the front end?

Advertisement

Answer

You want your java application to download a file from a given URL?

There is no need for user interactions.

See example below using Java NIO:

The Java NIO package offers the possibility to transfer bytes between 2 Channels without buffering them into the application memory.

To read the file from our URL, we’ll create a new ReadableByteChannel from the URL stream:

ReadableByteChannel readableByteChannel = Channels.newChannel(url.openStream());

The bytes read from the ReadableByteChannel will be transferred to a FileChannel corresponding to the file that will be downloaded:

FileOutputStream fileOutputStream = new FileOutputStream(FILE_NAME);

FileChannel fileChannel = fileOutputStream.getChannel();

We’ll use the transferFrom() method from the ReadableByteChannel class to download the bytes from the given URL to our FileChannel:

fileOutputStream.getChannel()
  .transferFrom(readableByteChannel, 0, Long.MAX_VALUE);

The transferTo() and transferFrom() methods are more efficient than simply reading from a stream using a buffer. Depending on the underlying operating system, the data can be transferred directly from the filesystem cache to our file without copying any bytes into the application memory.

On Linux and UNIX systems, these methods use the zero-copy technique that reduces the number of context switches between the kernel mode and user mode.

There are other libraries that you can use as well, that might be better than using Java NIO on its own.

Reference: https://www.baeldung.com/java-download-file

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement