下载Amazon S3文件返回空数据求助:SpringBoot+Vue Axios本地下载功能故障
问题修复方案
你当前的问题由前后端两处错误共同导致:后端接口默认将二进制流序列化为JSON格式返回,前端未指定响应接收类型且做了多余的JSON序列化处理,以下是具体修改方案:
一、后端代码修改
不要直接返回ByteArrayOutputStream,SpringBoot会默认将其序列化为JSON结构,你需要手动设置下载响应头,直接返回二进制流:
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; // 接口返回类型修改为ResponseEntity<byte[]> @GetMapping("/downloadSearchData") public ResponseEntity<byte[]> downloadSearchData() throws IOException { BasicAWSCredentials awsCredentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey); AmazonS3 s3client = AmazonS3ClientBuilder .standard() .withCredentials(new AWSStaticCredentialsProvider(awsCredentials)) .withRegion(awsRegion) .build(); String bucketName = "downloadable-cases"; String fileName = "7863784198_2021-08-16T13_30_06.690Z.json"; S3Object s3Object = s3client.getObject(bucketName, fileName); try (InputStream is = s3Object.getObjectContent(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { int len; byte[] buffer = new byte[4096]; while ((len = is.read(buffer, 0, buffer.length)) != -1) { outputStream.write(buffer, 0, len); } // 设置响应头,告知浏览器该请求为文件下载 HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\""); headers.add(HttpHeaders.CONTENT_TYPE, "application/octet-stream"); return new ResponseEntity<>(outputStream.toByteArray(), headers, HttpStatus.OK); } }
如果文件体积较大,建议直接将S3输入流写入HttpServletResponse的输出流,避免将整个文件加载到服务端内存导致OOM。
二、前端代码修改
Axios请求需要指定响应类型为blob,无需多余序列化响应数据:
import { saveAs } from 'file-saver' // 确保已安装file-saver依赖 downloadLocations() { axios.get("http://localhost:8080/api/v1/targetLocation/downloadSearchData", { responseType: 'blob' // 关键配置,指定响应为二进制流格式 }).then((response) => { const fileName = `test.json` // 也可从响应头content-disposition中提取后端返回的实际文件名 saveAs(response.data, fileName) }).catch((error) => { console.log(error); }); }
内容的提问来源于stack exchange,提问作者CodeJ
相关产品推荐
相关产品推荐

