Skip to content

Instantly share code, notes, and snippets.

@infomiho
Last active March 14, 2024 22:05
Show Gist options
  • Save infomiho/ec379df4e33f3ae3410a251ba3aa81af to your computer and use it in GitHub Desktop.
Save infomiho/ec379df4e33f3ae3410a251ba3aa81af to your computer and use it in GitHub Desktop.
Uploading files with Wasp 0.12.3
app fileUpload {
wasp: {
version: "^0.12.3"
},
title: "file-upload",
}
route RootRoute { path: "/", to: MainPage }
page MainPage {
component: import { MainPage } from "@src/MainPage.jsx"
}
apiNamespace fileUploadMiddleware {
middlewareConfigFn: import { addMiddleware } from "@src/apis.js",
path: "/api/upload"
}
api fileUpload {
httpRoute: (POST, "/api/upload"),
fn: import { uploadFile } from "@src/apis.js",
entities: []
}
{
"name": "fileUpload",
"dependencies": {
"wasp": "file:.wasp/out/sdk/wasp",
"react": "^18.2.0",
"multer": "1.4.5-lts.1"
},
"devDependencies": {
"typescript": "^5.1.0",
"vite": "^4.3.9",
"@types/react": "^18.0.37",
"prisma": "4.16.2",
"@types/multer": "*"
}
}
import { MiddlewareConfigFn } from "wasp/server";
import { FileUpload } from "wasp/server/api";
import multer from "multer";
const upload = multer({ dest: "uploads/" });
export const addMiddleware: MiddlewareConfigFn = (config) => {
config.set("multer", upload.single("file"));
return config;
};
export const uploadFile: FileUpload = (req, res) => {
console.log(req.body);
console.log(req.file);
const file = req.file!;
return res.json({
fileExists: !!file,
});
};
import { useState } from "react";
import "./Main.css";
import { api } from "wasp/client/api";
export const MainPage = () => {
const [name, setName] = useState("");
const [myFile, setMyFile] = useState();
const handleSubmit = async (e) => {
if (!myFile) {
alert("Please select a file");
return;
}
e.preventDefault();
const formData = new FormData();
formData.append("name", name);
formData.append("file", myFile);
try {
const data = await api.post("/api/upload", formData);
alert(JSON.stringify(data.data, null, 2));
} catch (err) {
console.log(err);
}
};
return (
<div className="container">
<main>
<h1>Uploading files with Wasp</h1>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="name">Name</label>
<input
type="text"
id="name"
name="name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="form-group">
<label htmlFor="my-file">My File</label>
<input
type="file"
id="my-file"
name="my-file"
onChange={(e) => setMyFile(e.target.files[0])}
/>
</div>
{myFile && (
<div className="form-group">
<strong>Selected file:</strong> {myFile.name}
</div>
)}
<button type="submit">Upload the file</button>
</form>
</main>
</div>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment