接口返回文件流

public ResponseEntity<InputStreamResource> meetingUserTemplate() throws FileNotFoundException {
        String path= UserController.class.getResource("/template/userTemplate.xlsx").getPath();
        File file = new File(path);
        InputStream inputStream = new FileInputStream(file);
        InputStreamResource resource = new InputStreamResource(inputStream);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+URLEncoder.encode("模版文件")+".xlsx");

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }

文件所在位置

注意controller层不要加@restController

 

posted @ 2023-11-15 15:37  杨吃羊  阅读(98)  评论(0)    收藏  举报