Understand there’s some limitations and I’m experimenting and getting no where. I appreciate anyone’s help. Some code / context below (note, none of these are right and more trying to illustrate the issues…):
It seems the following doesn’t work and strips the File data:
// I strip the File data so all you get is name="file_title.png"
const formData = await request.formData()
Okay, so lets try something harder:
// I strip the name and mime type...
const formData = await request.arrayBuffer()
// Try to rebuild...
var rebuiltDataisThisEvenPossible = base64CrazyFunctionOrPolyFillMagic(formData);
So finally why not just copy name/mimetype ideas from it KV Asset Handler and base it on the route:
// GET cat.png
// POST cat.png
let fileName = request.url.pathname // (not real code, none of this works)
let catUpdate = await KV_DEMO.put(fileName, await request.arrayBuffer())
return new Response('check console')
What’s the best practice for storing images/files in Cloudflare KV?
Limitations to getting Files from POST exist. If a Polyfill direction 1 or 2 rebuilding the ArrayBuffer to Base64 can potentially work, does anyone have an example of this? Is CPU time limts going to be an issue?
Currently sending images as Base64 pre-coded is my plan. Bringing this to the worker though would be awesome…
Disclosure: I am noob… Any dead-simple code is appreciated. Apologize if this is all over town
The bulk upload API has one more trick up its sleeve: not all data is a string. For example, you may have an image as a value, which is just a bag of bytes. if you need to write some binary data, you’ll have to base64 the value’s contents so that it’s valid JSON. You’ll also need to set one more key:
See: Test upload (will only be up for a day or so since it uses my account’s KV). After upload, you can go to /<filename> to see the file you uploaded.
It’s probably possible to go above 10mb with this upload since you can split an arrayBuffer but I don’t have much time to check that at the moment.
Wooo, brings a lot of peace to my mind knowing my sample code was in the right ballpark. Thanks for the detailed reply with your experience from this.
I never realized that form-encoded vs non-form-encoded POST-ing was a thing (TIL!).
This all makes perfect sense to me and I think this would potentially work for my use case / experiment. I will run some test tonight on this and am thankful for code sample + the working sample.
For everyone’s future reference:
Judge’s Working Code (key parts extracted)
// POST (non URL form encoded) to e.g.: /upload
let targetname = event.request.headers.get("x-filename") // could I guess be based on a wildcard route too: /uploads/cat.png
let buf = await event.request.arrayBuffer()
await STATIC_KV.put(targetname!, buf)