返回

axios 下载文件流 & 获取响应头 header content-disposition:解密 API 访问利器

前端

利用 Axios 优化与后端 API 的交互:文件流下载与响应头获取

文件流下载

与后端 API 交互时,经常需要下载文件流,例如 PDF 或图像。Axios 通过提供多种机制,让这一任务变得轻而易举。

首先,我们可以利用 responseType 属性将响应数据解析为 Blob 对象。Blob 对象是一种特殊的 JavaScript 对象,代表二进制数据,通常用于文件流。代码示例如下:

axios({
  url: 'http://example.com/file.pdf',
  method: 'GET',
  responseType: 'blob',
}).then((response) => {
  const blob = response.data;
  // 接下来处理下载文件流...
});

此外,Axios 还提供了 onDownloadProgress 事件监听器,可以让我们在下载过程中获取进度更新,从而实现进度条等功能。

最后,如果需要取消正在进行的下载请求,我们可以使用 cancelToken 属性。

获取响应头 Content-Disposition

处理文件流下载时,获取响应头的 Content-Disposition 字段至关重要。该字段包含有关下载文件的信息,例如文件名和文件类型。

Axios 提供了多种方式来访问响应头:

  • 通过 response.headers 对象直接获取所有响应头,包括 Content-Disposition
  • 通过设置 axios.defaults.headers.common['Content-Disposition'] 属性来获取 Content-Disposition

代码示例:

axios({
  url: 'http://example.com/api/data',
  method: 'GET',
}).then((response) => {
  const contentDisposition = response.headers['Content-Disposition'];
  console.log(contentDisposition);
});

应对 CORS 问题

跨域访问 API 时,可能会遇到 CORS(跨域资源共享)问题。Axios 通过在请求头中添加 Origin 字段来解决此问题,但这有时还不够。在这种情况下,需要在服务器端配置 CORS 策略以允许跨域访问。

示例代码

以下是使用 Axios 下载文件流和获取响应头的示例代码:

下载文件流:

axios({
  url: 'http://example.com/file.pdf',
  method: 'GET',
  responseType: 'blob',
}).then((response) => {
  const blob = response.data;
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = 'file.pdf';
  link.click();
  URL.revokeObjectURL(url);
});

获取响应头:

axios({
  url: 'http://example.com/api/data',
  method: 'GET',
}).then((response) => {
  const contentDisposition = response.headers['Content-Disposition'];
  console.log(contentDisposition);
});

常见问题解答

Q1:为什么下载文件时我收到了 Blob 对象而不是实际文件?

A1:Blob 对象代表二进制数据。要下载实际文件,您需要创建一个指向 Blob 对象的 URL,然后将该 URL 传递给一个包含 download 属性的 <a> 元素。

Q2:如何在 Axios 中使用 cancelToken 取消下载?

A2:创建 cancelToken 对象,然后将其作为 cancelToken 属性传递给 Axios 请求。要取消请求,请调用 cancelToken.cancel() 方法。

Q3:我无法在服务器端配置 CORS 策略。有什么其他解决方法吗?

A3:可以使用 CORS 代理服务或浏览器扩展来解决 CORS 问题。

Q4:我应该使用 response.headers 还是 axios.defaults.headers.common['Content-Disposition'] 来获取 Content-Disposition 头?

A4:response.headers 提供特定于当前请求的响应头,而 axios.defaults.headers.common['Content-Disposition'] 提供默认的 Content-Disposition 头。

Q5:如何处理大文件下载?

A5:对于大文件,可以使用流式传输技术,例如分块下载或 WebSockets。