【发布时间】:2020-08-15 09:43:53
【问题描述】:
我在前面使用带有 ReactJs 应用程序的 ASP.NET WebApi,我正在创建一个 Get 方法来从服务器下载文件,并且我尝试在响应标头中设置 Content-Type 和 Content-Length :
var result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(new MemoryStream(bytes));
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentLength = bytes.Length;
当我使用如下 fetch 方法从 ReactJs 应用程序调用此方法时:
await fetch(`someservice/${clientid}/download/${fileName}`, { responseType: "arraybuffer" })
.then((response) => {
const reader = response.body.getReader();
//get total length
const contentLength = response.headers.get('Content-Length');
console.log(response.headers);
//read the data
let receivedLength = 0; // received that many bytes at the moment
let chunks = []; // array of received binary chunks (comprises the body)
while (true) {
const { done, value } = reader.read();
if (done) {
break;
}
console.log(value);
chunks.push(value);
receivedLength += value.length;
console.log(`Received ${receivedLength} of ${contentLength}`)
}
//concatenate chunks into single Uint8Array
let chunksAll = new Uint8Array(receivedLength);
let position = 0;
for (let chunk of chunks) {
chunksAll.set(chunk, position);
position += chunk.length;
}
});
我收到了没有 Content-Type 和 Content-Length 标头的响应:
但是 Content-Type 和 Content-Length 不是有效的标头吗?
【问题讨论】:
标签: javascript reactjs asp.net-web-api http-headers