Spring Boot applications often need to provide some REST APIs to allow front-end applications to download images. We will introduce 2 different implementations. One is that when open the image URL is opened with a browser, the image will be downloaded into a file. The other is that the browser will directly display the image.
Table of Contents
Downloading Images as Files
If you want users to download the image directly into a file when clicking on the image URL on the front-end page, you can refer to the following method:
Displaying Images on Browsers
If you want images are displayed on browsers directly, you can use the follow method.
Create ImageResourceHttpRequestHandlerand inheritance ResourceHttpRequestHandler, the code is as follows:
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
@Component
public class ImageResourceHttpRequestHandler extends ResourceHttpRequestHandler {
public static final String ATTRIBUTE_FILE = "DOWNLOADING_FILE";
@Override
protected Resource getResource(HttpServletRequest request) {
File file = (File) request.getAttribute(ATTRIBUTE_FILE);
return new FileSystemResource(file);
}
}Create a controller to receive requests, and then let ImageResourceHttpRequestHandler handle the request.
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
@RestController
@RequestMapping("/images")
public class ImageController {
@Resource
private ImageResourceHttpRequestHandler imageResourceHttpRequestHandler;
@GetMapping("/download")
public void download(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws ServletException, IOException {
File file = new File("/path/to/image.jpg");
httpServletRequest.setAttribute(ImageResourceHttpRequestHandler.ATTRIBUTE_FILE, file);
imageResourceHttpRequestHandler.handleRequest(httpServletRequest, httpServletResponse);
}
}Open http://localhost:8080/images/download with a browser, and the image will be displayed directly on the browser.









