消费端通过 OpenFeign 调用服务端的导出接口,可以封装含有`byte[]`变量的实体类进行返回。
步骤如下:
**1. 在公共模块封装含有`byte[]`变量的实体类**
```java
@Data
public class ExportDTO {
private String filename;
private byte[] content;
}
```
**2. feign 接口返回 ExportDTO**
```java
@FeignClient(value = "assemb-server-provider", contextId = "googsClient")
public interface GoogsClient {
@GetMapping("/goods/logExport")
ExportDTO logExport();
}
```
**3. 服务端导出接口返回 ExportData**
```java
@RestController
public class GoodsController implements GoogsClient {
@Override
public ExportDTO logExport() {
try {
InputStream input = new FileInputStream(new File("f:/学生信息表.xlsx"));
ExportDTO dto = new ExportDTO();
dto.setFilename("学生信息表.xlsx");
dto.setContent(input.readAllBytes());
return dto;
} catch (IOException ex) {
return null;
}
}
}
```
**4. 消费端取出`byte[]`数据即可**
```java
@RestController
@RequiredArgsConstructor
public class GoodsController {
final GoogsClient googsClient;
@GetMapping("/goods/logExport")
public void logExport(HttpServletResponse response) throws IOException {
ExportDTO dto = googsClient.logExport();
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//防止中文文件名乱码
String fileName = URLEncoder.encode(dto.getFilename(), "utf-8").replaceAll("\\+", "%20");
response.setHeader("content-disposition", "attachment; filename=" + fileName);
response.setCharacterEncoding("utf-8");
//取出byte[]
response.getOutputStream().write(dto.getContent());
}
}
```