upload a file using Cloudflare Pages and SvelteKit
Hello,
I'm attempting to upload a file using Cloudflare Pages and SvelteKit. Below is the code snippet:
This code works locally, but on the production environment (Cloudflare Pages), the image is not an instance of File.
export const POST = async ({ request, locals }) => {
const formData = Object.fromEntries(await request.formData())
const image = formData.image
console.log(image)
/*
output on local environment:
File {
size: 15307,
type: 'image/png',
name: 'image.png',
lastModified: 1714500023653
}
output on prod environment (Cloudflare pages):
" PNG\r\n\u001a\n\u0000\u0000\u0000\rIHDR\u0000\u0000\u0001 \u0000\u0000\u0001 \b\u.....
*/
if (!(image instanceof File)) {
return json({ message: 'Invalid file' }, { status: 400 })
}
try {
const objectKey = `key-1234`
const uploadedImage = await locals.bucket.put(objectKey, image)
let key = uploadedImage.key
return json({ success: true, key: key }, { status: 200 })
} catch (e) {
return json({ message: e instanceof Error ? e.message : 'Failed to upload file ', err }, { status: 400 })
}
}
export const POST = async ({ request, locals }) => {
const formData = Object.fromEntries(await request.formData())
const image = formData.image
console.log(image)
/*
output on local environment:
File {
size: 15307,
type: 'image/png',
name: 'image.png',
lastModified: 1714500023653
}
output on prod environment (Cloudflare pages):
" PNG\r\n\u001a\n\u0000\u0000\u0000\rIHDR\u0000\u0000\u0001 \u0000\u0000\u0001 \b\u.....
*/
if (!(image instanceof File)) {
return json({ message: 'Invalid file' }, { status: 400 })
}
try {
const objectKey = `key-1234`
const uploadedImage = await locals.bucket.put(objectKey, image)
let key = uploadedImage.key
return json({ success: true, key: key }, { status: 200 })
} catch (e) {
return json({ message: e instanceof Error ? e.message : 'Failed to upload file ', err }, { status: 400 })
}
}
3 Replies
nvm, i found the solution in the docs:
https://developers.cloudflare.com/workers/configuration/compatibility-dates/#formdata-parsing-supports-file
Cloudflare Docs
Compatibility dates · Cloudflare Workers docs
Opt into a specific version of the Workers runtime for your Workers project.
@Evil Morty Did this actually solve the problem for you? I'm still running into the issue of the
File being converted into a string. In my case it's a PNGyes it did, show me your .toml file