'How to fetch file from azure blob using spring boot
I want to fetch files from Azure blob storage. Following code does it fine-
package com.<your-resource-group>.<your-artifact-name>;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.WritableResource;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
@RestController
@RequestMapping("blob")
public class BlobController {
@Value("azure-blob://<your-container-name>/<your-blob-name>")
private Resource blobFile;
@GetMapping("/readBlobFile")
public String readBlobFile() throws IOException {
return StreamUtils.copyToString(
this.blobFile.getInputStream(),
Charset.defaultCharset());
}
@PostMapping("/writeBlobFile")
public String writeBlobFile(@RequestBody String data) throws IOException {
try (OutputStream os = ((WritableResource) this.blobFile).getOutputStream()) {
os.write(data.getBytes());
}
return "file was updated";
}
}
My Question -
The @Value annotation provides value to the Resource that is static (i.e I cannot put any variable containing my path as a string inside @Value).
How can I implement the this
Solution 1:[1]
In application properties try storing the path
#application.properties
blob.path=
We can use @Value("${...property's name}")
annotation to access the above property in the Java class as follows:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ValueController {
@Value("${blob.path}")
private String path;
@GetMapping("")
..
}
}
Here try to use blob uri complete path in application properties and use the same in @value annotation as variable by map datatype
//
@Value("${blob.path}")
private Map<String, String> blobPath;
See this > java - How to read external properties based on value of local variable in Spring Boot? - Stack Overflow & Value Spring: Spring @Value annotation tricks - DEV Community
Also see Requestmapping
Other references :
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | kavyasaraboju-MT |