I'd be happy to help you integrate Vercel Blob storage with your Next.js project and implement the workflow you described. Let's break this down into steps and create the necessary components and functions.
Let's start by setting up Vercel Blob storage and creating the necessary components:
Now, let's go through the implementation and explain how it works:
uploadAndCreate
in app/actions/uploadAndCreate.ts
. This action handles both file upload to Vercel Blob and document creation in MongoDB 12.The uploadAndCreate
function does the following:
put
function from @vercel/blob
.UploadForm
in app/components/UploadForm.tsx
. This component renders a form for file upload and title input.UploadForm
component uses the uploadAndCreate
server action to handle form submission. It displays the result of the operation (success or error) to the user.app/page.tsx
) to include the UploadForm
component.To make this work, you need to set up the following environment variables:
BLOB_READ_WRITE_TOKEN
: Your Vercel Blob read-write token 1.MONGODB_URI
: Your MongoDB Atlas connection string.You can set these environment variables in your Vercel project settings or in a .env.local
file for local development.
Remember to replace 'your_database_name'
and 'your_collection_name'
in the uploadAndCreate
function with your actual MongoDB database and collection names.
This implementation covers your desired workflow:
You can further customize this implementation to fit your specific needs, such as adding more fields to the document or implementing error handling and validation.
I can help you optimize the media files and ensure they're not above 10 MB before uploading. We'll modify the existing code to include this functionality. Let's update our project to include file size checking and optimization.
Let's update our React Project to include file size checking and optimization:
Now, let's go through the changes and explain how the optimization works:
We've updated the uploadAndCreate
function in app/actions/uploadAndCreate.ts
:
optimizeImage
function that uses the sharp
library to optimize images 1.The optimization process:
sharp
to convert it to WebP format.In the UploadForm
component (app/components/UploadForm.tsx
):
formatFileSize
to display file sizes in a human-readable format.This implementation ensures that:
Remember to handle errors gracefully on the client side, especially for cases where a file can't be optimized to under 10 MB.
This solution provides a good balance between file size reduction and maintaining image quality. However, keep in mind that for very large images, the quality might be significantly reduced to meet the 10 MB limit. You may want to adjust the QUALITY_REDUCTION_STEP
or implement more sophisticated optimization strategies for specific use cases.