ZBLOG

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

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

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

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

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

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

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


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?