Fat32F
Deno9mo ago
Fat32

Help with File Uploads in Oak v17.1.4

Hi,
I’m currently working on a project and I’m trying to upload images to my backend using Deno and Oak. However, I'm encountering an issue where I get the following message:
"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/upload. (Reason: CORS header ‘Access-Control-Allow-Origin’ is missing). Status code: 500."
I’m confident that this isn’t a CORS issue because I’ve previously managed to send data to my backend without issues.
When checking the backend, I get the following error message:" TypeError - ctx.request.body is not a function "
This error indicates that in Oak v17.1.4, ctx.request.body is no longer a function, and I’m unsure how to handle file uploads correctly in this version.
Here is my current upload controller code:
"const uploadDir = "./Back_end/uploads";
await ensureDir(uploadDir);
export const uploadImage = async (ctx: Context) => {
const body = await ctx.request.body({ type: "form-data" });
const formData = await body.value;

for await (const [key, value] of formData.entries()) {
if (value instanceof File) {
const content = await value.arrayBuffer();
const uint8Array = new Uint8Array(content);

const uploadDir = "./images"; // set your correct path here
const destPath = path.join(uploadDir, value.name);
await Deno.writeFile(destPath, uint8Array);

ctx.response.status = 200;
ctx.response.body = { message: "Image uploaded", fileName: value.name };
console.log("Image successfully uploaded:", value.name);
return;
}
}
ctx.response.status = 400;
ctx.response.body = { message: "No file received" };
console.log("No file received");
};"
Could someone please advise on how to properly handle file uploads with Oak v17.1.4?
Thank you in advance for your help!
Was this page helpful?