Shannor
Shannor
CDCloudflare Developers
Created by Shannor on 8/12/2024 in #workers-help
How to use a worker to download an image into R2
Hello, My team and I are using a worker with the itty-router to act as a small server. We have a requirement now where we need to get a list of urls, take those urls and download the images to our R2 storage. We're trying to do it now but when we try it looks as if our fetch doesn't even fire at all. Here is a code snippet.
const imageArrayBuffer = await fetch(
imageUrl,
{
method: "GET",
redirect: "follow",
},
);
const temp = await imageArrayBuffer.arrayBuffer();

// Cache the image in our CDN
const r2Object = await this.bucket.put(
`images/${imageRef}`,
temp,
);

if (!r2Object) {
throw new Error("Failed to cache image in R2");
}
const imageArrayBuffer = await fetch(
imageUrl,
{
method: "GET",
redirect: "follow",
},
);
const temp = await imageArrayBuffer.arrayBuffer();

// Cache the image in our CDN
const r2Object = await this.bucket.put(
`images/${imageRef}`,
temp,
);

if (!r2Object) {
throw new Error("Failed to cache image in R2");
}
We never get past the fetch. This call is also nested pretty deep within the router. So it's not at the top level index.js but about 3 - 4 functions deep if that's relevant.
8 replies