From fbbd3535a797e17589eaa5a85dbe5399c1fb5327 Mon Sep 17 00:00:00 2001 From: Don Xavier Date: Tue, 7 Jan 2025 12:25:19 +0530 Subject: [PATCH] Implement multiple File uploading --- src/hooks/useFileUpload.tsx | 41 ++++++++++++++++++- .../Encounters/tabs/EncounterFilesTab.tsx | 9 +++- 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/src/hooks/useFileUpload.tsx b/src/hooks/useFileUpload.tsx index d8aea1fa1b1..d570e164dbb 100644 --- a/src/hooks/useFileUpload.tsx +++ b/src/hooks/useFileUpload.tsx @@ -1,6 +1,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query"; import imageCompression from "browser-image-compression"; import { t } from "i18next"; +import jsPDF from "jspdf"; import { ChangeEvent, DetailedHTMLProps, @@ -97,6 +98,33 @@ export default function useFileUpload( const [files, setFiles] = useState([]); const queryClient = useQueryClient(); + const generatePDF = async (files: File[]): Promise => { + try { + const pdf = new jsPDF(); + for (const [index, file] of files.entries()) { + const imgData = await new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => resolve(reader.result as string); + reader.onerror = () => reject("Error reading file"); + reader.readAsDataURL(file); + }); + + pdf.addImage(imgData, "JPEG", 10, 10, 190, 0); + if (index < files.length - 1) pdf.addPage(); + } + + const pdfBlob = pdf.output("blob"); + const pdfFile = new File([pdfBlob], "combined.pdf", { + type: "application/pdf", + }); + + console.log("Generated PDF file:", pdfFile); // Log the generated file + return pdfFile; + } catch (error) { + console.error("Error generating PDF:", error); + return null; + } + }; const onFileChange = (e: ChangeEvent): any => { if (!e.target.files?.length) { return; @@ -238,8 +266,19 @@ export default function useFileUpload( if (!validateFileUpload()) return; setProgress(0); + let filesToUpload = files; + + if (files.length > 1) { + const pdfFile = await generatePDF(files); + if (pdfFile) { + filesToUpload = [pdfFile]; + } else { + console.error("Failed to generate PDF from multiple files."); + return; + } + } - for (const [index, file] of files.entries()) { + for (const [index, file] of filesToUpload.entries()) { const filename = allowNameFallback && uploadFileNames[index] === "" && file ? file.name diff --git a/src/pages/Encounters/tabs/EncounterFilesTab.tsx b/src/pages/Encounters/tabs/EncounterFilesTab.tsx index 053637b75d8..8d979bc912e 100644 --- a/src/pages/Encounters/tabs/EncounterFilesTab.tsx +++ b/src/pages/Encounters/tabs/EncounterFilesTab.tsx @@ -136,6 +136,7 @@ export const EncounterFilesTab = (props: EncounterTabProps) => { ], allowNameFallback: false, onUpload: () => refetch(), + multiple: true, }); useEffect(() => { @@ -543,8 +544,12 @@ const FileUploadDialog = ({
- - {fileUpload.files?.[0]?.name} + {fileUpload.files?.map((file, index) => ( +
+ + {file.name} +
+ ))}