Spring: Difference between revisions

From Chorke Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
Line 16: Line 16:
     *    </ul>
     *    </ul>
     */
     */
     @GetMapping(value = "/{prefix}/**")
     @GetMapping("/{prefix}/**")
     public void fetch(
     public void fetch(
             @PathVariable("prefix") final String prefix,
             @PathVariable("prefix") final String prefix,

Revision as of 21:58, 14 November 2022

Multiple Slash Path Variable

@RestController
@RequestMapping("/api/file")
public class FileController {
    @Autowired
    FileService fileService;

    /**
     * File download requests handler
     *
     * @param prefix of relative file path
     *    <ul>
     *        <li>certificates/Policy-8691-191939b9-526b-4933-b05c-61e672609dcc.pdf</li>
     *        <li>certificates/extras/Policy_Wording.pdf</li>
     *    </ul>
     */
    @GetMapping("/{prefix}/**")
    public void fetch(
            @PathVariable("prefix") final String prefix,
            final HttpServletResponse response,
            final HttpServletRequest request
    ) {
        String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String name = (!ObjectUtils.isEmpty(prefix)) ? path.substring(path.indexOf(prefix)) : null;
        try {
            if (!ObjectUtils.isEmpty(name)) {
                InputStream inputStream = fileService.fetch(name);
                OutputStream outputStream = response.getOutputStream();
                IOUtils.copy(inputStream, outputStream);
            } else throw new FileNotFoundException(name);
        } catch (IOException e) {
            throw new InternalServerException(e.getMessage(), e);
        }
    }
}

References