,可以通过以下步骤完成:
@GetMapping
或@RequestMapping
注解来指定请求路径和方法。在方法中,可以通过使用ResponseEntity
来返回字节数组,并设置相应的Content-Type
和Content-Disposition
头信息。示例代码如下:
@GetMapping("/download")
public ResponseEntity<byte[]> downloadFile() throws IOException {
// 从文件系统或数据库获取字节数组
byte[] fileBytes = getFileBytes();
// 设置响应头信息
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", "filename.ext");
return new ResponseEntity<>(fileBytes, headers, HttpStatus.OK);
}
axios
库发送HTTP请求并获取字节数组数据。在Vue组件中,可以通过调用API接口来触发下载操作,并处理返回的字节数组。示例代码如下:
// 安装axios依赖(如果尚未安装)
// npm install axios
import axios from 'axios';
export default {
methods: {
downloadFile() {
axios({
url: '/api/download',
method: 'GET',
responseType: 'arraybuffer', // 设置响应类型为字节数组
}).then((response) => {
const contentDisposition = response.headers['content-disposition'];
const filename = contentDisposition
.split(';')
.find((part) => part.trim().startsWith('filename='))
.split('=')[1]
.trim();
const blob = new Blob([response.data], {
type: response.headers['content-type'],
});
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.click();
}).catch((error) => {
console.error(error);
});
},
},
};
上述代码中,axios
发送GET请求获取字节数组,设置responseType
为arraybuffer
,以便正确处理二进制数据。然后,通过创建一个Blob对象和一个下载链接,将字节数组转换为文件并触发下载操作。
这样,从Spring Boot下载字节数组到Vue前端的过程就完成了。
在腾讯云产品中,推荐使用对象存储服务 COS(腾讯云对象存储),通过该服务可以更方便地存储和管理文件,并提供灵活的权限控制、CDN加速、数据迁移等功能。你可以在腾讯云官网的COS产品介绍页面了解更多相关信息。
领取专属 10元无门槛券
手把手带您无忧上云