在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助手提供,问题来源于学员提问