Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect page to static file in Spring Boot?

How can I redirect a page web request / request mapping in Spring Boot (MVC) to point to a static file (example: .txt, .json, .jpg, .mp4, etc). All I have in my Spring Boot project is an application.properties file and the @Controllers.

I'd like for the user, when making a web request to the url in browser to be asked to download the file (not use it to attempt to render the page, like it does with .html, .jsp)

like image 669
code Avatar asked Oct 22 '25 06:10

code


1 Answers

You can achive this by telling the response that you wish to attach a downloadable file. Then you can simple write the content you want to make downloadable.

Here is an example :

@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/myredirect", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public void downloadFile(HttpServletResponse response) {
    // Remove this instruction if you wish to disable the download dialog.
    response.setHeader("Content-Disposition", "attachment; filename=filename.ext");

    // Load your file content as byte.
    byte[] fileContent = IOUtils.toByteArray(new ClasspathResource("myfile").getIntputStream());

    response.getOutputStream().write(fileContent);
}

On the other hand, if you simply want a direct mapping to a static file. You may use the default public folder of Spring Boot Starter Web.

Any file found inside classpath:/public will be mapped to /*by default.

like image 107
Daniel Lavoie Avatar answered Oct 23 '25 20:10

Daniel Lavoie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!