How to process and save Uploaded File on server side

I see examples for the frontend on how to upload a file, but how do I process and save the file on the backend using SolidJs or SolidStart?
1 Reply
Antebios
Antebios2mo ago
Update: I figured it out myself!!! This is just my proof-of-concept code: Client code:
import { saveFile } from "~/lib/utility";
const handlerFileUpload = async (formData: FormData) =>
await saveFile(formData);

function handleFile() {
... {your code to get the file from your UI}
const selectFile = {your code to return File}

const fileForm = new FormData();
fileForm.append("file", selectedFile);
log.debug("File Form: ", fileForm);
handlerFileUpload(fileForm);
}
import { saveFile } from "~/lib/utility";
const handlerFileUpload = async (formData: FormData) =>
await saveFile(formData);

function handleFile() {
... {your code to get the file from your UI}
const selectFile = {your code to return File}

const fileForm = new FormData();
fileForm.append("file", selectedFile);
log.debug("File Form: ", fileForm);
handlerFileUpload(fileForm);
}
Server code: ~/lib/utility.ts
import * as process from "process";
import { promisify } from "util";
import { writeFile } from "fs";

export async function saveFile(formData: FormData) {
"use server";
const writeFileAsync = promisify(writeFile);

const currentWorkingDirectory = process.cwd();
log.debug("currentWorkingDirectory: ", currentWorkingDirectory);
const tempDir = `${currentWorkingDirectory}\\public\\assets\\temp`;

try {
const file = formData.get("file") as File;
const fileName = file.name;
const writePath = `${tempDir}\\${fileName}`;
const fileArrayBuffer = await file.arrayBuffer();
await writeFileAsync(writePath, Buffer.from(fileArrayBuffer));
} catch (error) {
console.error("Error saving file:", error);
}
}
import * as process from "process";
import { promisify } from "util";
import { writeFile } from "fs";

export async function saveFile(formData: FormData) {
"use server";
const writeFileAsync = promisify(writeFile);

const currentWorkingDirectory = process.cwd();
log.debug("currentWorkingDirectory: ", currentWorkingDirectory);
const tempDir = `${currentWorkingDirectory}\\public\\assets\\temp`;

try {
const file = formData.get("file") as File;
const fileName = file.name;
const writePath = `${tempDir}\\${fileName}`;
const fileArrayBuffer = await file.arrayBuffer();
await writeFileAsync(writePath, Buffer.from(fileArrayBuffer));
} catch (error) {
console.error("Error saving file:", error);
}
}
I did a test wit both text and binary file, and then compared to the original files and they all matched.
Want results from more Discord servers?
Add your server