Spring: Difference between revisions
Jump to navigation
Jump to search
No edit summary |
|||
Line 1: | Line 1: | ||
==Multiple Slash Path Variable== | |||
<source lang="java"> | |||
@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(value = "/{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); | |||
} | |||
} | |||
} | |||
</source> | |||
==References== | ==References== |
Revision as of 20:29, 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(value = "/{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
| ||