spring-boot二进制文件下载

小编最近在Web项目中,需要完成一个excel文件导入和导出的功能。导入没有什么问题,但是导出折腾了小编半天时间。spring-boot在这里有个坑,谁踩谁知道啊!不说废话,先看spring-boot下载功能的实现代码。为了代码复用,我将上传和下载对应的功能,放在了一个抽象的Controller类中,需要该功能的controller可以直接集成这个类,并且实现两个abstract的方法即可。

    abstract public class UploadAndDownloadController {

    private Logger logger = LoggerFactory.getLogger(UploadAndDownloadController.class);

    /**
     * Download response entity.
     *
     * @param id the id
     * @return the response entity
     */
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<byte[]> download(@RequestParam(value = "id", required = false) List id) {
        File file = generate(parseId(id));
        try {
            return ControllerUtil.createBytesResponse("download.xls", file);
        } catch (Exception e) {
            logger.error("文件下载失败", e);
            return null;
        } finally {
            file.delete();
        }
    }

    /**
     * Upload response entity.
     *
     * @param file the file
     * @return the response entity
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity upload(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                introduce(file.getInputStream());
            } catch (Exception e) {
                logger.error("文件导入失败", e);
                return ControllerUtil.createFileUploadFailureResponse("文件导入失败");
            }
        }
        return ControllerUtil.createFileUploadSuccessResponse();
    }

    /**
     * Generate file.
     *
     * @param id the id
     * @return the file
     */
    protected abstract File generate(List id);

    /**
     * Introduce.
     *
     * @param in the in
     */
    protected abstract void introduce(InputStream in);

    protected abstract File getTemplateFile() throws IOException;

    private List parseId(List id) {
        if (id == null) {
            return null;
        }
        return id.stream().filter(s -> {
            try {
                Long.parseLong(s);
            } catch (Exception e) {
                return false;
            }
            return true;
        }).map(Long::parseLong).collect(Collectors.toList());
    }
}

接下来,才是最重要的一步,没有下面的设置,上面的下载功能就是废的,下载下来的二进制文件全是乱码。请看下面的代码。下面的代码扩展了WebMvcConfigurerAdapter,并添加了基于字节的http消息转换器(默认只有基于字符的http消息转换器,所以如果不加这个,下载后的二进制文件全是乱码)。

@Configuration
public class CustomWebAppConfigurer extends WebMvcConfigurerAdapter {
    @Override
    public void configureMessageConverters(List> converters) {
    //此处是重点啊,亲们
        converters.add(new ByteArrayHttpMessageConverter());
        super.configureMessageConverters(converters);
    }
}

你可能感兴趣的:(java,spring-boot)