const cacheName = 'my-cache';
export async function cacheFile(key: string, response: Response): Promise<void> {
try {
const cache: Cache = await caches.open(cacheName);
const clonedResponse = response.clone(); // 克隆响应对象
await cache.put(key, clonedResponse);
// // 将响应体转换为可重复读取的 Blob 对象
// const blob = await response.blob();
// const clonedResponse = new Response(blob, response);
// await cache.put(key, clonedResponse); // 将克隆的响应对象放入缓存
console.log(`PDF 已缓存: ${key}`);
} catch (error) {
console.error('缓存操作发生错误:', error);
}
}
export async function getCachedFile(key: string): Promise<Response | null> {
try {
const cache: Cache = await caches.open(cacheName);
const response: Response | undefined = await cache.match(key);
if (response) {
console.log(`从缓存中获取 PDF: ${key}`);
return response;
}
console.log(`未找到缓存的 PDF: ${key}`);
return null;
} catch (error) {
console.error('缓存操作发生错误:', error);
return null;
}
}
为什么我把文件写入缓存时,报错:
const fileName = url!.substring(url!.lastIndexOf('/') + 1);
const cachedFile = await getCachedFile(fileName)
let response:Response
if(cachedFile){
response = cachedFile
} else {
response = await fetch(serverURL + url!,{cache: 'force-cache'});
cacheFile(fileName,response)
}
// const response = cachedFile ?? await fetch(serverURL + url!,{cache: 'force-cache'});
pdfData = await response.arrayBuffer();
一直报错如下:
缓存操作发生错误: TypeError: Failed to execute 'clone' on 'Response': Response body is already used
at cacheFile (cacheFun.ts:7:41)