如何在 Cloudflare Worker 中使用 fetch() 下载文件?

问题描述 投票:0回答:1

我正在创建一个 cloudflare 工作程序,使用 fetch 从我的托管服务器下载文件,但我不断收到此错误。

Promise 类型不正确:Promise 未解析为“Response”。

我已经添加了整个脚本以供参考。我是新手,请大家帮忙!

const homepage = `
<!DOCTYPE html>
<html>
<body>
<button href="/download.aspx">Download</button>
<body>
</html>`;

async function download() {
  let url = 'https://club-mavic.xyz/a.pdf';
  var options = {
    method: 'GET',
    redirect: 'follow'
  };
  let res;
  for (let i = 0; i < 3; i++) {
    res = await fetch(url, options);
    if (res.ok) {
      break;
    }
    sleep(800 * (i + 1));
  }    
  if (res.ok) {
    const {
      headers
    } = res = new Response(res.body, res)
    headers.set("Content-Disposition", `attachment; filename=a.pdf`);
    headers.set("Content-Length", 1525);
    headers.append('Access-Control-Allow-Origin', '*');
    headers.set('Content-Disposition', 'inline');
    return res;
  } else {
    const details = await res.text()
    return new Response(details, {})
  }
}

async function handleRequest(request, event) {
let url = new URL(request.url);
let path = url.pathname;
if (path == '/') {
  return new Response(homepage, {
    status: 200,
    headers: {
      "content-type": "text/html;charset=UTF-8",
    },
  })
} else if (path == '/download.aspx') {
  download();
}
}

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request, event).catch(
    (err) => new Response("Report this page when asked at the time of support... ==> " + err.stack, { status: 500 })
  )
  );
});
javascript web-worker cloudflare-workers
1个回答
0
投票

要在 Cloudflare Worker 中使用 fetch() 下载文件,您可以使用 Workers 环境提供的 fetch() 函数。这是一个示例代码片段:

javascript

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  // Replace 'URL_OF_YOUR_FILE' with the actual URL of the file you want to download
  const fileUrl = 'URL_OF_YOUR_FILE';

  // Fetch the file
  const fileResponse = await fetch(fileUrl);

  // Check if the request was successful (status code 200)
  if (fileResponse.ok) {
    // Extract content type from the original response headers
    const contentType = fileResponse.headers.get('content-type');

    // Create a new response with the file content and content type
    return new Response(fileResponse.body, {
      status: fileResponse.status,
      statusText: fileResponse.statusText,
      headers: {
        'Content-Type': contentType,
        // You can add other headers if needed
      },
    });
  } else {
    // If the request to the file URL was not successful, return an errorresponse
    return new Response(`Failed to fetch file:  ${fileResponse.statusText}`, {
      status: fileResponse.status,
      statusText: fileResponse.statusText,
    });
  }
}

将“URL_OF_YOUR_FILE”替换为您要下载的文件的实际 URL。该脚本将获取文件并返回具有相同内容和内容类型的新响应。

请记住,Cloudflare Workers 在无服务器环境中运行,并且需要考虑一些限制,例如执行时间和内存限制。此外,如果文件非常大,您可能需要流式传输响应,而不是立即将整个文件加载到内存中。

© www.soinside.com 2019 - 2024. All rights reserved.