In Node.js we could use,
req.on("data", (data) => console.log(`on data: ${data.length}`));
req.on("close", () => console.log("req closed"));
req.on("aborted", () => console.log("req aborted"));
req.on("error", (err) => console.log("req error", err));
I've switched to Deno using it for a long time but on a file upload purpose, I need to handle user abort or any kind of network issue to handle the upload data correctly.
This is my current code,
//imports
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { Application, Router } from 'https://deno.land/x/oak/mod.ts';
...
...
router.post("/upload", async (ctx) => {
try{
//get file from multipart form
const body = ctx.request.body({ type: "form-data" });
console.log("File upload started");
const form = await body.value.read({ maxFileSize: 100*1024*1024, outPath: './uploads'});
console.log(form);
ctx.response.status = 200;
ctx.response.body = { path: "file.filename" };
//get file from form
if (!form.files || !form.files.length) {
ctx.response.status = 400;
ctx.response.body = { msg: "No file provided" };
return;
}
const file = form.files[0];
//return file path
ctx.response.status = 200;
ctx.response.body = { path: file.filename };
} catch (error) {
console.log(error);
ctx.response.status = 500;
ctx.response.body = { msg: error.message };
}
});
// Start the combined server
console.log("Booting server...");
//socket-io handler
const handler = io.handler(async (req) => {
return await app.handle(req) || new Response(null, { status: 404 });
});
await serve(handler, {
port: httpPort,
});
The file is stored in disk rather than loading it all in memory. So if user aborts the file upload while it was being uploaded the file gets saved with the available data. So I need to remove this file from disk in this case.
I have no idea how to do it.