Skip to content

Instantly share code, notes, and snippets.

@ewalk153
Created April 18, 2024 02:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ewalk153/644245f9832ee1d22d9a72338279cdeb to your computer and use it in GitHub Desktop.
Save ewalk153/644245f9832ee1d22d9a72338279cdeb to your computer and use it in GitHub Desktop.
Remix demo of a CSV file upload
import type { ActionFunctionArgs, UploadHandler } from "@remix-run/node";
import {
json,
unstable_createMemoryUploadHandler as createMemoryUploadHandler,
unstable_parseMultipartFormData as parseMultipartFormData,
} from "@remix-run/node";
import { useFetcher } from "@remix-run/react";
type ActionData = {
errorMsg?: string;
text?: string;
imgDesc?: string;
};
export const action = async ({ request }: ActionFunctionArgs) => {
const uploadHandler = createMemoryUploadHandler({
maxPartSize: 500_000,
});
const formData = await parseMultipartFormData(request, uploadHandler);
const file = formData.get("csv_file");
const imgDesc = formData.get("desc");
console.log(imgDesc);
if (!file) {
return json({
errorMsg: "Something went wrong while uploading",
});
}
const text = await new Response(file).text()
return json({
text,
imgDesc,
});
};
export default function Index() {
const fetcher = useFetcher<ActionData>();
return (
<>
<fetcher.Form method="post" encType="multipart/form-data">
<label htmlFor="csv-field">Image to upload</label>
<input id="csv-field" type="file" name="csv_file" accept=".csv" />
<label htmlFor="csv-desc">Image description</label>
<input id="csv-desc" type="text" name="desc" />
<button type="submit">Upload</button>
</fetcher.Form>
{fetcher.state === "idle" && fetcher.data ? (
fetcher.data?.errorMsg ? (
<h2>{fetcher.data?.errorMsg}</h2>
) : (
<>
<div>
File has been uploaded:
</div>
<div> description: {fetcher.data?.imgDesc || "Uploaded csv"} </div>
<pre>{fetcher.data?.text}</pre>
</>
)
) : null}
</>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment