Spring MVC 上传下载
本文最后更新于 947 天前,其中的信息可能已经有所发展或是发生改变。

上传

@PostMapping("/import")
public ResponseCode<Boolean> importFile(@RequestParam(value = "file") MultipartFile multipartFile) {
    try (InputStream inputStream = multipartFile.getInputStream()) {
        //TODO
    } catch (IOException e) {
        e.printStackTrace();
    }
    return ResponseCode.success();
}

下载

@GetMapping("/template/{suffix}")
public ResponseEntity<InputStreamResource> template(@PathVariable("suffix") String suffix) throws IOException {
    ClassPathResource resource = new ClassPathResource(String.format("files/template.%s", suffix));
    Assert.isTrue(resource.exists(), "文件不存在");
    return ResponseEntity.ok()
            .headers(e -> {
                e.setContentDisposition(ContentDisposition.builder("attachment").filename(String.format("template.%s", suffix), StandardCharsets.UTF_8).build());
                e.setCacheControl(CacheControl.noCache().mustRevalidate());
                e.setPragma("no-cache");
                e.setExpires(0);
            })
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .contentLength(resource.contentLength())
            .body(new InputStreamResource(resource.getInputStream()));
}
如果觉得本文对您有帮助,记得收藏哦~
上一篇
下一篇