返回文件流
@Service
@Slf4j
public class FileService {
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);
}
}