Omari Celestine
Omari Celestine

Reputation: 1435

How to Upload Files to Digital Ocean Spaces using NodeJS?

I am trying to upload files to DigitalOcean Spaces using NodeJSm multer and the S3 package. When I try to upload a file, the file is created on DigitalOcean Spaces but it has a size of zero (0).

This is a snippet of the code that I am using:

import aws from 'aws-sdk';
import { S3Client } from '@aws-sdk/client-s3';
import multerS3 from 'multer-s3';

const s3Config = new S3Client(
    {
        forcePathStyle: false,
        endpoint: env.DO_SPACES_ENDPOINT,
        region: env.DO_SPACES_REGION,
        credentials: {
            accessKeyId: env.DO_SPACES_KEY,
            secretAccessKey: env.DO_SPACES_SECRET
        }
    }
);

export const storage = multerS3(
    {
        s3: s3Config,
        bucket: env.DO_SPACES_NAME,
        acl: 'public-read',
        metadata: function(req, file, cb) {
            cb(null, { fieldName: file.fieldname });
        },
        key: function(req, file, cb) {
            cb(null, file.originalname);
        },
        
    }
);

export const standardFileUploader = multer({
   storage: storage,
   limits: {
       fileSize: maxUploadFileSize
   },
});

export const uploadStandardFile = (field: string) => {
    const upload = standardFileUploader.single(field);

    return async (req: any, res: any, next: NextFunction) => {
        upload(req, res, (error) => {
            if (error instanceof multer.MulterError)
            {
                if (error.code === 'LIMIT_FILE_SIZE')
                {
                    return 'Error';
                }
                else if (error.code === 'LIMIT_UNEXPECTED_FILE')
                {
                    console.log(error);
                    
                    return 'Error';
                }

                console.log(error);
                
                // A Multer error occurred when uploading.
                return 'Error';
            }
            else if (error)
            {
                console.log(error);
                // An unknown error occurred when uploading.
                return 'Error';
            }

            return next();
        });
    };
};

What could possibly be the issue and how can I solve it?

Upvotes: 0

Views: 117

Answers (0)

Related Questions