ZBLOG

react 如何拿到响应标头的Content-Disposition: attachment; filename=OPHotelListAdvertising_???_240628192348584_240628192348584.json的filename的值

在React中,可以通过XMLHttpRequest对象或Fetch API来发送HTTP请求,并获取响应标头中的Content-Disposition字段。

使用XMLHttpRequest对象的示例代码如下:

const xhr = new XMLHttpRequest();
xhr.open('GET', 'your_api_endpoint');
xhr.onload = function() {
  if (xhr.status === 200) {
    const contentDisposition = xhr.getResponseHeader('Content-Disposition');
    const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
    if (filenameMatch && filenameMatch[1]) {
      const filename = decodeURIComponent(filenameMatch[1].replace(/['"]/g, ''));
      console.log(filename); // 输出文件名
    }
  }
};
xhr.send();

使用Fetch API的示例代码如下:

fetch('your_api_endpoint')
  .then(response => {
    const contentDisposition = response.headers.get('Content-Disposition');
    const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
    if (filenameMatch && filenameMatch[1]) {
      const filename = decodeURIComponent(filenameMatch[1].replace(/['"]/g, ''));
      console.log(filename); // 输出文件名
    }
    return response;
  })
  .then(data => {
    // 处理响应数据
  });

以上代码将从服务器获取响应,并解析Content-Disposition标头中的filename值。请替换”your_api_endpoint”为你实际的API地址。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=16084

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?