Spring Boot ResponseEntity文件下载:手机端乱码或无法打开问题排查
本文分析一个使用Spring Boot和JavaScript实现文件下载的案例,该案例在电脑端正常,但在手机端下载的文件却无法打开或出现乱码。后端使用ResponseEntity返回文件流,前端使用标签触发下载。
问题描述: 后端Spring Boot应用返回文件流,电脑端下载正常,但手机端下载的文件打开失败或显示乱码。后端设置了Content-Disposition header。
后端代码 (示例):
HttpStatus statusCode = HttpStatus.OK;HttpHeaders headers = new HttpHeaders();if (download) { String filename = new String(r.getName().getBytes(), "iso8859-1"); // 潜在问题点1 headers.add("Content-Disposition", "attachment;filename=" + filename); // 潜在问题点2}Resource resource = resourceLoader.getResource("file:" + path + "/" + id);InputStream in = resource.getInputStream();byte[] body = new byte[in.available()]; // 潜在问题点3in.read(body);ResponseEntity<byte[]> streamResponse = new ResponseEntity<>(body, headers, statusCode);return streamResponse;
登录后复制
本文来自互联网或AI生成,不代表软件指南立场。本站不负任何法律责任。