Search code examples
next.jssupabase

Uploading a file to Supabase storage using Nextjs and formidable


I am trying to upload a file to Supabase using the Nextjs API route and formidable. Below is the code:

form.parse(req, async (err, fields, files) => {
            if (err) {
                console.error('Error', err)
                throw err
            }
            const {data, error} = await supabase 
                .storage
                .from('apg-bucket')
                .upload(files.image.originalFilename, files.image, {
                    contentType: files.image.mimetype,
                    cacheControl: '3600',
                    upsert: false,
                })

The problem is when the file gets uploaded into Supabase this is 0-150 bytes rather than the total size of the file (7937 bytes). See below:

SupabaseImageUpload

From logging I can see that the file is coming into the API via the form and is being captured by formidable. See below:

ConsoleLogNextJS

Wondering what I am doing wrong and the reason why the full file doesn't get uploaded into the storage bucket?

Have tried to change the file variable in the Supabase upload from:

  • files.image[0]
  • files.image.filepath
  • files[0]

All the above did is change the byte value within Supabase to 0 - 50 bytes rather than the entire image.

Thanks, Jake


Solution

  • Just updating this and have figured out the solution.

    Solution below

    form.parse(req, async (err, fields, files) => {
            if (err) {
                console.error('Error', err)
                throw err
            } else {
                console.log('Files:', files.image.filepath)
    
                const fileContent = await fs.promises.readFile(files.image.filepath)  //this is what was missing!
    
                const { data, error } = await supabase
                    .storage
                    .from('apg-bucket')
                    .upload(files.image.originalFilename, fileContent, {
                        contentType: files.image.mimetype,
                        cacheControl: '3600',
                    })
                
            }
    

    Turns out the fs module was needed otherwise the file content doesn't get attached within the call.