spring-boot二进制文件下载

本文介绍如何在Spring Boot中实现文件的导入与导出功能,特别是解决导出Excel文件时出现的乱码问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

小编最近在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<String> 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<JSONObject> 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<Long> id);

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

    protected abstract File getTemplateFile() throws IOException;

    private List<Long> parseId(List<String> 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<HttpMessageConverter<?>> converters) {
    //此处是重点啊,亲们
        converters.add(new ByteArrayHttpMessageConverter());
        super.configureMessageConverters(converters);
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值