Skip to content

Commit

Permalink
Add example to README
Browse files Browse the repository at this point in the history
  • Loading branch information
a179346 committed Feb 28, 2024
1 parent 545d4aa commit 3a985f2
Showing 1 changed file with 87 additions and 3 deletions.
90 changes: 87 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,93 @@
npm i nextjs-chunk-upload-action
```

## 📖 Usage
```js
To be added
## 📖 Usage / Example

Demo Repository: [nextjs-chunk-upload-action-demo](https://github.com/a179346/nextjs-chunk-upload-action-demo)

```ts
// upload-form.tsx

"use client";

import { ChunkUploader } from "nextjs-chunk-upload-action";

import { chunkUploadAction } from "./chunk-upload-action";

export function UploadForm() {
const handleFormAction = (formData: FormData) => {
const file = formData.get("file") as File;
if (!file) return;
const uploader = new ChunkUploader({
file,
onChunkUpload: chunkUploadAction,
metadata: { name: file.name },
onChunkComplete: (bytesAccepted, bytesTotal) => {
console.log("Progress:", `${bytesAccepted} / ${bytesTotal}`);
},
onError: (error) => {
console.error(error);
},
onSuccess: () => {
console.log("Upload complete");
},
});
uploader.start();
};

return (
<form
className="flex flex-col items-center justify-center"
action={handleFormAction}
>
<input
name="file"
type="file"
className="p-4 border-2 border-dashed rounded-lg"
/>
<button
type="submit"
className="mt-4 p-2 bg-blue-500 text-white rounded-lg"
>
Upload
</button>
</form>
);
}
```

```ts
// chunk-upload-action.ts

"use server";

import { createWriteStream } from "fs";
import { join } from "path";

export async function chunkUploadAction(
base64Chunk: string,
offset: number,
metadata: { name: string }
) {
const buffer = Buffer.from(base64Chunk, "base64");
const path = join("./uploads", metadata.name);

const writeable = createWriteStream(
path,
offset === 0
? { flags: "w" }
: {
flags: "r+",
start: offset,
}
);
return new Promise<void>((resolve, reject) => {
writeable.on("finish", () => resolve());
writeable.on("error", reject);
writeable.write(buffer);
writeable.end();
});
}
```

## 🤝 Contributing
Expand Down

0 comments on commit 3a985f2

Please sign in to comment.