Back

How to upload PDF into appwrite bucket react native

  • 0
  • Android
  • React Native
  • Storage
Cm7
8 Jan, 2025, 00:13

I created an app and am trying to upload PDF into appwrite storage bucket and fetch it back but currently my issue is in uploading the PDF to appwrite storage bucket here is the upload function const handleUpload = async () => { if (!validateFields() || !pdf) { setErrors((prevErrors) => ({ ...prevErrors, pdf: 'Please select a PDF file.' })); return; }

try { const fileId = pdfMetadata ? pdfMetadata.fileId : 'unique()';

TypeScript
// Fetch and convert the file to a Blob
const response = await fetch(pdf.uri);
const fileBlob = await response.blob();

// Upload the file
const uploadResponse = await storage.createFile('pdfs_bucket', fileId, fileBlob);

// Generate a public URL for the uploaded file
const publicURL = storage.getFilePreview('pdfs_bucket', uploadResponse.$id);

if (pdfMetadata) {
  // Update existing document
  await databases.updateDocument('Coou_App', 'Pdf_metadata', pdfMetadata.$id, {
    faculty,
    department,
    level,
    semester,
    course,
    pdf_url: publicURL.href,
  });
  Alert.alert('Success', 'PDF Updated successfully!');
} else {
  // Create a new document
  await databases.createDocument('Coou_App', 'Pdf_metadata', 'unique()', {
    faculty,
    department,
    level,
    semester,
    course,
    pdf_url: publicURL.href,
  });
  Alert.alert('Success', 'PDF Uploaded successfully!');
}

// Reset state
setPdfMetadata({});
setActionButtonText('Update PDF');

} catch (err) { setErrors((prevErrors) => ({ ...prevErrors, upload: err.message || 'Failed to upload PDF.', })); } };

TL;DR
Developers want to upload a PDF into an Appwrite bucket in React Native. They need to use the Appwrite React Native SDK. Ensure code is wrapped in backticks for better formatting. The provided function handles the PDF upload process, including fetching, converting to Blob, uploading, and generating a public URL. Error handling is included.
Steven
8 Jan, 2025, 00:18

FYI, it's best to wrap code in backticks to format a bit nicer. You can use 1 backtick for inline code (https://www.markdownguide.org/basic-syntax/#code) and 3 backticks for multiline code (https://www.markdownguide.org/extended-syntax/#syntax-highlighting).

Steven
8 Jan, 2025, 00:19

are you using the Appwrite react native SDK?

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more