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!
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!
1 replies
upload files
I am working on a web development project, and in this project, I have a constraint that says I cannot use any frameworks. However, for my site, I need to upload images. For example, in my case, the user should be able to send images to my backend so that I can use them later on my site. How can I do this with Deno? If you could tell me how to do it and provide a small preview example, that would be great, please.
1 replies