Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

feat: add browser file upload; increase file size limit to 30 MB

Marc Seitz3e48dd1bf059
diff --git a/components/document-upload.tsx b/components/document-upload.tsx
index 6711d786..06732af6 100644
--- a/components/document-upload.tsx
+++ b/components/document-upload.tsx
@@ -3,6 +3,7 @@ import { useDropzone } from "react-dropzone";
import { ArrowUpTrayIcon, DocumentIcon, PhotoIcon } from "@heroicons/react/24/outline";
import { DocumentTextIcon, PresentationChartBarIcon } from "@heroicons/react/20/solid";
import { bytesToSize } from "@/lib/utils";
+import { toast } from "sonner"
function fileIcon(fileType: string) {
switch (fileType) {
@@ -32,19 +33,25 @@ export default function DocumentUpload({
}) {
const { getRootProps, getInputProps } = useDropzone({
accept: {
- "image/*": [".png", ".gif", ".jpeg", ".jpg"],
"application/pdf": [], // ".pdf"
- "application/msword": [], // ".doc"
- "application/vnd.ms-powerpoint": [], // ".ppt"
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
- [], // ".docx"
- "application/vnd.openxmlformats-officedocument.presentationml.presentation":
- [], // ".pptx"
},
multiple: false,
- onDrop: (acceptedFiles) => {
+ maxSize: 30 * 1024 * 1024, // 30 MB
+ onDropAccepted: (acceptedFiles) => {
setCurrentFile(acceptedFiles[0]);
},
+ onDropRejected: (fileRejections) => {
+ const { errors } = fileRejections[0];
+ let message;
+ if (errors[0].code === "file-too-large") {
+ message = "File size too big (max. 30 MB)"
+ } else if (errors[0].code === "file-invalid-type") {
+ message = "File type not supported (.pdf only)"
+ } else {
+ message = errors[0].message
+ }
+ toast.error(message);
+ },
});
const imageBlobUrl = useMemo(
@@ -92,7 +99,7 @@ export default function DocumentUpload({
<p className="text-xs leading-5 text-gray-400">
{currentFile
? "Replace file?"
- : ".pdf, .docx, .pptx, image files and more"}
+ : "Only *.pdf & 30 MB limit"}
</p>
</div>
</div>
diff --git a/components/documents/add-document-modal.tsx b/components/documents/add-document-modal.tsx
index 6e37cff4..ff2681ba 100644
--- a/components/documents/add-document-modal.tsx
+++ b/components/documents/add-document-modal.tsx
@@ -8,14 +8,11 @@ import {
} from "@/components/ui/dialog";
import { useState } from "react";
import { useRouter } from "next/router";
-// @ts-ignore
-import type { PutBlobResult } from "@vercel/blob";
+import { put, type PutBlobResult } from "@vercel/blob";
import { toast } from "sonner";
import DocumentUpload from "@/components/document-upload";
import { pdfjs } from "react-pdf";
import { getExtension } from "@/lib/utils";
-import { get } from "http";
-import { set } from "date-fns";
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
@@ -24,7 +21,7 @@ export function AddDocumentModal({children}: {children: React.ReactNode}) {
const [uploading, setUploading] = useState<boolean>(false);
const [currentFile, setCurrentFile] = useState<File | null>(null);
- const handleSubmit = async (event: any) => {
+ const handleBrowserUpload = async (event: any) => {
event.preventDefault();
// Check if the file is chosen
@@ -33,34 +30,22 @@ export function AddDocumentModal({children}: {children: React.ReactNode}) {
return; // prevent form from submitting
}
- const data = new FormData();
- if (currentFile) data.append("file", currentFile);
-
try {
setUploading(true);
- // upload the file to the blob storage
- const blobResponse = await fetch("/api/file/upload", {
- method: "POST",
- body: data,
+ const newBlob = await put(currentFile.name, currentFile, {
+ access: "public",
+ handleBlobUploadUrl: "/api/file/browser-upload",
});
- if (!blobResponse.ok) {
- throw new Error(`HTTP error! status: ${blobResponse.status}`);
- }
-
- // get the blob url from the response
- const blob = (await blobResponse.json()) as PutBlobResult;
-
let response: Response | undefined;
let numPages: number | undefined;
// create a document in the database if the document is a pdf
- if (getExtension(blob.pathname).includes("pdf")) {
-
- numPages = await getTotalPages(blob.url);
- response = await saveDocumentToDatabase(blob, numPages);
+ if (getExtension(newBlob.pathname).includes("pdf")) {
+ numPages = await getTotalPages(newBlob.url);
+ response = await saveDocumentToDatabase(newBlob, numPages);
} else {
- response = await saveDocumentToDatabase(blob);
+ response = await saveDocumentToDatabase(newBlob);
}
if (response) {
@@ -78,15 +63,13 @@ export function AddDocumentModal({children}: {children: React.ReactNode}) {
setTimeout(() => {
router.push("/documents/" + document.id);
- }, 4000);
+ setUploading(false);
+ }, 2000);
}
-
} catch (error) {
console.error("An error occurred while uploading the file: ", error);
- } finally {
- setUploading(false);
}
- };
+ }
async function saveDocumentToDatabase(blob: PutBlobResult, numPages?: number) {
// create a document in the database with the blob url
@@ -130,7 +113,7 @@ export function AddDocumentModal({children}: {children: React.ReactNode}) {
</div>
<form
encType="multipart/form-data"
- onSubmit={handleSubmit}
+ onSubmit={handleBrowserUpload}
className="flex flex-col"
>
<div className="space-y-12">
diff --git a/components/welcome/upload.tsx b/components/welcome/upload.tsx
index 2199347e..ab934fe4 100644
--- a/components/welcome/upload.tsx
+++ b/components/welcome/upload.tsx
@@ -1,13 +1,16 @@
import { useRouter } from "next/router";
import { motion } from "framer-motion";
-import { useEffect, useState } from "react";
-// @ts-ignore
-import type { PutBlobResult } from "@vercel/blob";
-import DocumentUpload from "../document-upload";
+import { useState } from "react";
+import { put, type PutBlobResult } from "@vercel/blob";
+import DocumentUpload from "@/components/document-upload";
import { ArrowRightIcon, DocumentDuplicateIcon } from "@heroicons/react/24/outline";
import { toast } from "sonner";
import Skeleton from "../Skeleton";
import { STAGGER_CHILD_VARIANTS } from "@/lib/contants";
+import { pdfjs } from "react-pdf";
+import { getExtension } from "@/lib/utils";
+
+pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
export default function Upload() {
const router = useRouter();
@@ -18,7 +21,7 @@ export default function Upload() {
const [currentDocId, setCurrentDocId] = useState<string | null>(null);
const [copiedLink, setCopiedLink] = useState<boolean>(false);
- const handleSubmit = async (event: any) => {
+ const handleBrowserUpload = async (event: any) => {
event.preventDefault();
// Check if the file is chosen
@@ -27,41 +30,49 @@ export default function Upload() {
return; // prevent form from submitting
}
- const data = new FormData();
- if (currentFile) data.append("file", currentFile);
-
try {
setUploading(true);
- // upload the file to the blob storage
- const blobResponse = await fetch("/api/file/upload", {
- method: "POST",
- body: data,
+ const newBlob = await put(currentFile.name, currentFile, {
+ access: "public",
+ handleBlobUploadUrl: "/api/file/browser-upload",
});
- if (!blobResponse.ok) {
- throw new Error(`HTTP error! status: ${blobResponse.status}`);
- }
-
- // get the blob url from the response
- const blob = (await blobResponse.json()) as PutBlobResult;
-
setCurrentFile(null);
setCurrentBlob(true);
- setTimeout(async () => {
- await createLink(blob.pathname, blob.url);
- }, 2000);
+ let response: Response | undefined;
+ let numPages: number | undefined;
+ // create a document in the database if the document is a pdf
+ if (getExtension(newBlob.pathname).includes("pdf")) {
+ numPages = await getTotalPages(newBlob.url);
+ response = await saveDocumentToDatabase(newBlob, numPages);
+ } else {
+ response = await saveDocumentToDatabase(newBlob);
+ }
- setUploading(false);
+
+ if (response) {
+ const document = await response.json();
+ const linkId = document.links[0].id;
+
+ setTimeout(() => {
+ setCurrentDocId(document.id);
+ setCurrentLinkId(linkId);
+ setUploading(false);
+ }, 2000);
+ }
} catch (error) {
- console.error(error);
+ console.error("An error occurred while uploading the file: ", error);
setCurrentFile(null);
setUploading(false);
}
};
- const createLink = async (name: string, url: string) => {
+ const saveDocumentToDatabase = async (
+ blob: PutBlobResult,
+ numPages?: number
+ ) => {
// create a document in the database with the blob url
const response = await fetch("/api/documents", {
method: "POST",
@@ -69,8 +80,9 @@ export default function Upload() {
"Content-Type": "application/json",
},
body: JSON.stringify({
- name: name,
- url: url,
+ name: blob.pathname,
+ url: blob.url,
+ numPages: numPages,
}),
});
@@ -78,13 +90,14 @@ export default function Upload() {
throw new Error(`HTTP error! status: ${response.status}`);
}
- const document = await response.json();
- const linkId = document.links[0].id;
- setCurrentDocId(document.id);
- setCurrentLinkId(linkId);
- return true;
+ return response;
};
+ // get the number of pages in the pdf
+ async function getTotalPages(url: string): Promise<number> {
+ const pdf = await pdfjs.getDocument(url).promise;
+ return pdf.numPages;
+ }
const handleCopyToClipboard = (id: string) => {
navigator.clipboard
@@ -130,7 +143,7 @@ export default function Upload() {
<main className="mt-8">
<form
encType="multipart/form-data"
- onSubmit={handleSubmit}
+ onSubmit={handleBrowserUpload}
className="flex flex-col"
>
<div className="space-y-12">
@@ -204,9 +217,7 @@ export default function Upload() {
<div className="relative">
<div className="flex py-8 rounded-md shadow-sm">
<div className="flex w-full max-w-xs sm:max-w-lg focus-within:z-10">
- <p
- className="block w-full md:min-w-[500px] rounded-none rounded-l-md px-4 text-left border-0 py-1.5 text-gray-200 bg-gray-900 leading-6 overflow-y-scroll"
- >
+ <p className="block w-full md:min-w-[500px] rounded-none rounded-l-md px-4 text-left border-0 py-1.5 text-gray-200 bg-gray-900 leading-6 overflow-y-scroll">
{`${process.env.NEXT_PUBLIC_BASE_URL}/view/${currentLinkId}`}
</p>
</div>
diff --git a/pages/api/file/browser-upload.ts b/pages/api/file/browser-upload.ts
new file mode 100644
index 00000000..52163d68
--- /dev/null
+++ b/pages/api/file/browser-upload.ts
@@ -0,0 +1,57 @@
+import { handleBlobUpload, type HandleBlobUploadBody } from "@vercel/blob";
+import type { NextApiResponse, NextApiRequest } from "next";
+import { getServerSession } from "next-auth/next";
+import { authOptions } from "../auth/[...nextauth]";
+import { CustomUser } from "@/lib/types";
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse
+) {
+ const body = JSON.parse(req.body) as HandleBlobUploadBody;
+
+ try {
+ const jsonResponse = await handleBlobUpload({
+ body,
+ request: req,
+ onBeforeGenerateToken: async (pathname: string) => {
+ // Generate a client token for the browser to upload the file
+
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ res.status(401).end("Unauthorized");
+ throw new Error("Unauthorized");
+ }
+
+ return {
+ allowedContentTypes: ["application/pdf"],
+ maximumSizeInBytes: 30 * 1024 * 1024, // 30 MB
+ metadata: JSON.stringify({
+ // optional, sent to your server on upload completion
+ userId: (session.user as CustomUser).id,
+ }),
+ };
+ },
+ onUploadCompleted: async ({ blob, metadata }) => {
+ // Get notified of browser upload completion
+ // ⚠️ This will not work on `localhost` websites,
+ // Use ngrok or similar to get the full upload flow
+
+ console.log("blob upload completed", blob, metadata);
+
+ try {
+ // Run any logic after the file upload completed
+ // const { userId } = JSON.parse(metadata);
+ // await db.update({ avatar: blob.url, userId });
+ } catch (error) {
+ // throw new Error("Could not update user");
+ }
+ },
+ });
+
+ return res.status(200).json(jsonResponse);
+ } catch (error) {
+ // The webhook will retry 5 times waiting for a 200
+ return res.status(400).json({ error: (error as Error).message });
+ }
+}