I want to implement a REST method GET in a Spring Boot application which delivers a file being of different types.
For example it could return a PDF document, a JPEG image, a TIF image, etc., in fact what ever there is.
How to do this? Shall I specify the return type as Object:
@GetMapping("/document")
public Object getDocument() {
file = ... logic to retrieve a specific file (PDF, JPEG, TIF, ...)
return file;
}
And what has the Client side to do with the returned value, to make the right file type out of it?
Cheers
You should create new class to specify response. It should be something like:
public class Response{
public String type;
public Byte[] fileContent
... getter/setter/constructor etc
}
This idea should be fine for small files (images or pdf). With large files it becomes more complicated
By Spring I think you meant spring-mvc. you can do something like this
@RequestMapping(value = "{fileName:.+}", method = RequestMethod.GET)
@ResponseBody
public void getImageSling(@PathVariable String fileName, HttpServletResponse response)throws IOException {
//read the file in byte[]
//evaluate content type you want to set
response.setContentType(contentType);
response.getOutputStream().write(byteStream.getByteStream());
response.getOutputStream().flush();
}
For the purpose of delivering different view representations for different client requests there is notion of view resolvers in Spring MVC.
Particularly you need to configure ContentNegotiationViewResolver
and friends according to your supported document extension types.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.