D
Deno

help

How to uploading images from frontend to Deno.serve()

MMqx11/15/2023
Hey, can someone please give me a vanilla code example on how to upload files from my frontend application to the server that uses Deno.serve(). I know how to upload the image in the frontend and send it to the Deno backend using a POST request, but how can I work with this image on the server side? Currently my backend is set up without any framework. Thanks! This is currently my code:
import { readAll } from "https://deno.land/std@0.104.0/io/util.ts";

const pictures_folder = Deno.env.get("DENO_PICTURES_FOLDER") || "src/public/src/img";

export async function uploadGinPicture(req: Request) {

if (!req.body) {
return new Response(null, { status: 400 });
}
const fileName = "0";

const body = await readAll(req.body);

await Deno.writeFile(`${pictures_folder}/${fileName}.png`, body);

return new Response(JSON.stringify({ worked: true }), { status: 200 });
}
import { readAll } from "https://deno.land/std@0.104.0/io/util.ts";

const pictures_folder = Deno.env.get("DENO_PICTURES_FOLDER") || "src/public/src/img";

export async function uploadGinPicture(req: Request) {

if (!req.body) {
return new Response(null, { status: 400 });
}
const fileName = "0";

const body = await readAll(req.body);

await Deno.writeFile(`${pictures_folder}/${fileName}.png`, body);

return new Response(JSON.stringify({ worked: true }), { status: 200 });
}
@Deno AI Helper
DAHDeno AI Helper11/15/2023
Sure, I'd be happy to help. Could you please provide me with the question you'd like me to answer?
MMqx11/15/2023
Hey, can you please give me a vanilla code example on how to upload files from my frontend application to the server that uses Deno.serve(). I know how to upload the image in the frontend and send it to the Deno backend using a POST request, but how can I work with this image on the server side? Currently my backend is set up without any framework. Thanks!
DAHDeno AI Helper11/15/2023
Sure, I can help with that. On the server side, you can use the fetch API to receive the uploaded file. The fetch API is part of the global scope in Deno, and it's compatible with the fetch API in the browser. When you receive a fetch event, you can call event.request.formData() to parse the incoming form data. This will return a FormData object, which you can use to access the uploaded files. Here's a basic example of how you can do this:
addEventListener("fetch", async (event) => {
if (event.request.method === "POST") {
const formData = await event.request.formData();
const imageFile = formData.get("image");
if (imageFile instanceof File) {
console.log(`Received image with name ${imageFile.name}`);
// You can read the file content as follows:
const content = await imageFile.arrayBuffer();
// Now you can work with the content, for example save it to a file:
await Deno.writeFile(`./${imageFile.name}`, new Uint8Array(content));
}
}
event.respondWith(new Response("ok"));
});
addEventListener("fetch", async (event) => {
if (event.request.method === "POST") {
const formData = await event.request.formData();
const imageFile = formData.get("image");
if (imageFile instanceof File) {
console.log(`Received image with name ${imageFile.name}`);
// You can read the file content as follows:
const content = await imageFile.arrayBuffer();
// Now you can work with the content, for example save it to a file:
await Deno.writeFile(`./${imageFile.name}`, new Uint8Array(content));
}
}
event.respondWith(new Response("ok"));
});
In this example, we're listening for fetch events. When we receive a POST request, we parse the form data and get the uploaded file. We then log the file name and read the file content. Finally, we write the file content to a new file in the current directory. Please note that you'll need to run your script with the --unstable and --allow-read flags because the FormData API and the Deno.writeFile API are currently unstable and require read access respectively. Also, please replace "image" with the actual field name you're using to upload the file in your frontend application. I hope this helps! Let me know if you have any other questions. 🦕
LLeokuma11/17/2023
I'm not sure what exactly you mean by "work with this image", but you can manipulate it as a blob:
const imgBlob = await request.blob();
const imgBlob = await request.blob();
You could also manipulate it as a Uint8Array
MMqx11/23/2023
Okay thanks 👍🏻 I don’t want to manipulate it. I just want to save the image on the server side as a for example png file

Looking for more? Join the community!

Recommended Posts
Deno Deploy JSON importI'm using zod-i18n-map library for error translation, which requires an import for the library itselMost efficient way to broadcast messages globally across main script and workers?I basically want a simple message bus that is global to all my workers + the main script, without reWhat is the process for deploying a jupyter notebook made using deno?I have webdev experience and was using Observable. I was looking for alternatives that use javascripPostGraphile on DenoDoes PostGraphile work with Deno? Trying to see if I can run PostGraphile as a serverless function oIs there any way to disable Deno's Intellisense feature without disabling Deno itself?When programming with Deno, I've noticed how relatively slow the lang server is, and I need intellisDeploying Lume to github pagesI'm totaly new to this, but have been following instructions to build a site with lume. It works locBest hardware for Deno development?I am looking for a new laptop / desktop for Deno development as my current setup seems no longer viaHow do I make the crypto.subtle.digest algo flexible?This is a learning moment, bear with me. 😅 I can hard code an algo for the digest like this: ```twhat’s the current best practice for bundling?Is it deno esbuild? Wondering what supports npm specifiers and bundling atmHow do I get a d.ts file to be used?I'm extending a type from `hono` by adding that code in a `hono.d.ts` file in my `src` folder. ```“Log streaming API” on Deno DeployWhat does “Log streaming API” refers to in the analytics section of the pricing page of Deno Deploy?Read-only FS detectionHi, I have few deps that by default create cache/log dirs... I can disable it, but the detection itsIs there a built-in parser for the string that Deno.inspect produces?I found out in another thread that Deno.inspect(myObj) produces a visually gorgeous string representHow to get the nice Deno console.log format into a string?When I do a console.log on an instantiated class object, I get a beautiful format in the terminal, tbyonm - force use of DenoWhen I use byonm enabled in my deno.json, and say I have a vite project triggered from a package.jsoCan I disable deno linting for individual files, or a path?I'm using VSCode and the Deno extension. I want to use the inbuilt functionality of VSCode for type Rust run JS/TSHow can I embed this project into a rust application so that rust can run js ts and has runtime api Set-Cookie - Header shows as "deleted"I am trying to use deno to script/scrape a website. I can successfully log in to the site (using fet