How do you upload a file from a worker using rust?

Hi, there. I can send a request using Fetch and a JsValue containing JSON, but I can’t send a file. Is there support for multipart form data?

Hey,

You can pass in a FormData to fetch. So you could do something like this:

export default {
  fetch(req) {
    // Create a new FormData instance
    const data = new FormData();

    // Fetch a file from KV (or whatever you would like)
    const fileData = await KV.get('some_file', 'arrayBuffer');    

    // Append the ArrayBuffer to the FormData
    data.append('file', file);

    // Now we can send the request
    fetch('https://example.com', {
      method: 'POST',
      body: data,
    });
  }
}

References:

If you need any more help, the Discord is active with a lot of helpful users :slight_smile:
Invite: Cloudflare Workers

2 Likes

I meant on rust; FormData can’t be used as a RequestInit body. It requires an Option of JsValue which can be constructed from an array of bytes, but I don’t know how to create it properly.

Oh sorry, I missed that in the title. I’d recommend going to the Discord and asking in the #workers-rs channel.

1 Like