How effectively download file by url and convert to org.springframework.core.io.Resource?

318 Views Asked by At

I have a link that opens a file. The file can be a pdf or an image. I need to load this file and then use it in a service like org.springframework.core.io.Resource.

My code downloads a file and saves it to the repository folder. But it strictly specifies the extension and file name.

public org.springframework.core.io.Resource downloadWithJavaNIO(String fileURL, String localFilename) {
    URL url = new URL(fileURL);
    try (ReadableByteChannel readableByteChannel = Channels.newChannel(url.openStream());
         FileOutputStream fileOutputStream = new FileOutputStream(localFilename);
         FileChannel fileChannel = fileOutputStream.getChannel()
    ) {
        fileChannel.transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
    }

    // TODO converting to org.springframework.core.io.Resource
    return null;
}

Can I somehow automatically determine the extension and file name? .pdf/.png and so on. Is there any way to convert it to org.springframework.core.io.Resource without the stage of saving to the repository?

What would be the best way to solve my problem?

1

There are 1 best solutions below

0
Jiandong On

Spring does provide some Resource implementations.

try to us FileUrlResource and let us know it works or not.

Resource resource = new FileUrlResource(new URL(fileURL));