makeItEasier
makeItEasier

Reputation: 216

Get the Path of a resource from a spring boot aplication using servlet context

I have this structure, generated by spring boot

enter image description here

So I want to get a input stream of the file gastos.xlsx using sevletContext.

    @Autowired
    private ServletContext context;

    @GetMapping("/grafico")
    public ResponseEntity<String> exportExcelGrafico(HttpServletResponse response){

        try{
               //this path returns null. What is the real path to put here? 
             InputStream input = context.getResourceAsStream("src/main/resources/templates/gastos.xlsx");
             //returns null
             input = context.getResourceAsStream("/resources/templates/gastos.xlsx");
             // Returns null
             input = context.getResourceAsStream("/templates/gastos.xlsx");
        }
        catch(){

        }

What would be the right path? I didn't configure anything on my application.properties

Upvotes: 1

Views: 1758

Answers (1)

JB Nizet
JB Nizet

Reputation: 692141

What's in the src/main/resources folder of your Maven or Gradle project ends up in your jar, not in the web resources. And it should thus be loaded using the class loader, not using the servlet context:

MyClass.class.getResourceAsStream("/templates/gastos.xlsx")

Not sure why you put that file under templates, since... it's not a template.

Upvotes: 1

Related Questions