电脑下载正常,手机却乱码?ResponseEntity文件下载问题的解决方案
许多开发者在开发文件下载功能时,会遇到一个棘手的问题:电脑端下载的文件可以正常打开,但手机端却无法打开或显示乱码。本文将分析一个基于ResponseEntity的文件下载案例,并提供相应的解决方案。
案例分析:
后端使用ResponseEntity返回文件流,并设置Content-Disposition头部信息指定文件名。关键代码如下:
HttpStatus statusCode = HttpStatus.OK;HttpHeaders headers = new HttpHeaders();if (download) { String filename = new String(r.getName().getBytes(), "iso8859-1"); headers.add("Content-Disposition", "attachment;filename=" + filename);}Resource resource = resourceLoader.getResource("file:" + path + "/" + id);InputStream in = resource.getInputStream();byte[] body = new byte[in.available()];in.read(body);ResponseEntity<byte[]> streamResponse = new ResponseEntity<>(body, headers, statusCode);return streamResponse;
登录后复制
本文来自互联网或AI生成,不代表软件指南立场。本站不负任何法律责任。