Change Content-Length for file downloads

Hello! I am trying to change the Content-Length header, as I will use Cloudflare Workers to download files from a R2 bucket. I tried by changing the header manually, but it doesnt make a change. Then I read that it was not possible to change that header, and that the only way to do so is by using Streams. Now, my question is how should I do that? I tried to do it (see the code below), however it does not work. Any advice is very much appreciated!
firmwareBin = await env.R2.get(decodeURI(key));
let { readable, writable } = new FixedLengthStream(175104);
firmwareBin.body.pipeTo(writable);
return new Response(readable, firmwareBin);
firmwareBin = await env.R2.get(decodeURI(key));
let { readable, writable } = new FixedLengthStream(175104);
firmwareBin.body.pipeTo(writable);
return new Response(readable, firmwareBin);
1 Reply
Geektrader|ForexHistoryData.com
To change the Content-Length header in a Cloudflare Worker when serving files from an R2 bucket, you should use a FixedLengthStream to create a stream with a specified length. However, your current code snippet is missing a few steps. Here's how you can modify it: firmwareBin = await env.R2.get(decodeURI(key)); let { readable, writable } = new FixedLengthStream(175104); // You need to create a new Response object with the readable stream // and set the headers you want to modify or keep from the original response. let newHeaders = new Headers(firmwareBin.headers); newHeaders.set('Content-Length', '175104'); // Set the desired Content-Length // Pipe the original body to the writable stream of the FixedLengthStream. await firmwareBin.body.pipeTo(writable); // Return a new Response with the readable stream from the FixedLengthStream // and the new headers. return new Response(readable, { headers: newHeaders, status: firmwareBin.status, statusText: firmwareBin.statusText }); Make sure to replace '175104' with the actual length of the content you want to serve. This code creates a new Response object with the readable stream from the FixedLengthStream and sets the Content-Length header to the desired value. It also preserves the original status and status text from the firmwareBin response.