How to upload a file from the client or from postman to the server? #667
-
Hey everyone, I am using deno and oak to upload files to my database (KV). But I got question and an issue. What is the best way to be able to send a file to the database? I see most of people are storing tempFiles in the server and then sending it to the DB. I am trying to achieve the first piece which is the temporary storage, but I am getting errors. This is my server.ts: // server.ts
import { Application, Router } from "https://deno.land/x/oak/mod.ts";
import { ensureDir } from "https://deno.land/std/fs/mod.ts";
import { join } from "https://deno.land/std/path/mod.ts";
import { crypto } from "https://deno.land/std/crypto/mod.ts";
const app = new Application();
const router = new Router();
const uploadDir = './uploads';
await ensureDir(uploadDir);
router.post('/upload', async (context) => {
if (context.request.hasBody) {
const body = await context.request.body({ type: 'form-data' }).value;
const rspBody = { fields: 0, files: 0 };
for (const [name, value] of body.entries()) {
if (value instanceof File) {
const newFileName = crypto.randomUUID();
const filePath = join(uploadDir, newFileName + '-' + value.name);
await Deno.writeFile(filePath, new Uint8Array(await value.arrayBuffer()));
rspBody.files++;
} else {
rspBody.fields++;
}
}
context.response.body = rspBody;
} else {
context.response.status = 400;
context.response.body = { error: "No file uploaded" };
}
});
app.use(router.routes());
app.use(router.allowedMethods());
console.log("Server is running on port 8000");
await app.listen({ port: 8000 }); But I am getting the error i the line 15, it says in the `.request.body( -> No quick fixes available
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
You are using the "old" API for accessing the request body (prior to version v13) but you are using the "latest" version of oak by not being explicit in what version you are using. With versions of oak v13 and later you have to use the correct API as per the documentation: https://jsr.io/@oak/oak/doc/body/~/Body (which is what the error is indicating to you too, that you aren't using the API correctly). If you want the form data, it would be something like: const body = await context.request.body.formData(); Or use a version of oak prior to v13. |
Beta Was this translation helpful? Give feedback.
You are using the "old" API for accessing the request body (prior to version v13) but you are using the "latest" version of oak by not being explicit in what version you are using. With versions of oak v13 and later you have to use the correct API as per the documentation: https://jsr.io/@oak/oak/doc/body/~/Body (which is what the error is indicating to you too, that you aren't using the API correctly).
If you want the form data, it would be something like:
Or use a version of oak prior to v13.