0%

springboot返回文件流

返回文件流

@Service
@Slf4j
public class FileService {

    /**
     * @param fileName 文件名
     */
    public void getFile(String fileName, HttpServletResponse response) {
        try (FileInputStream inputStream = new FileInputStream(new File(fileName));
             OutputStream outputStream = response.getOutputStream();) {
            byte[] data = new byte[inputStream.available()];
            inputStream.read(data);
            // 文件格式未知字节流
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Length", "" + data.length);
            // 设置文件名
            response.setHeader( "Content-Disposition","attachment; filename=" + fileName);
            outputStream.write(data);
            outputStream.flush();
        } catch (Exception e) {
            log.error("get File {} error, {}", fileName, e);
        }
    }
}
@RestController
public class FileController {

    @Autowired
    FileService fileService;

    @GetMapping("/file")
    public void getFile(@RequestParam(value = "fileName") String fileName,
                           HttpServletResponse response) {
        fileService.getFile(fileName, response);
    }
}