0

To upload the files to the node.js server, I am using a multer package. The files are uploading, but the path in the database only saves the file name.

I want it to be saved in the database where it was uploaded. In my case, I'm uploading the files here: Project/public/uploads/related_directory

The multer middleware:

export const UPLOADS_DIR = path.join(__dirname, '..', '..', 'public', 'uploads');
const PROFILE_PIC_DIR = path.join(UPLOADS_DIR, 'profile_pictures');
const PRODUCT_DIR = path.join(UPLOADS_DIR, 'products');
const CATEGORY_DIR = path.join(UPLOADS_DIR, 'category');

createDirectoryIfNotExists(PROFILE_PIC_DIR);
createDirectoryIfNotExists(PRODUCT_DIR);
createDirectoryIfNotExists(CATEGORY_DIR);

function createDirectoryIfNotExists(directoryPath: string) {
    if (!fs.existsSync(directoryPath)) {
        try {
            fs.mkdirSync(directoryPath, { recursive: true });
        } catch (error) {
            console.error(`Unable to create directory: ${directoryPath}`);
            process.exit(1);
        }
    }
}

let destination = '';
const storage: StorageEngine = multer.diskStorage({
    destination: (req: Request, file: Express.Multer.File, callback: (error: Error | null, destination: string) => void) => {
        const fieldName = file.fieldname;

        if (fieldName === 'profile_pic') {
            destination = PROFILE_PIC_DIR;
        } else if (fieldName === 'product') {
            destination = PRODUCT_DIR;
        } else if (fieldName === 'category') {
            destination = CATEGORY_DIR;
        } else {
            destination = UPLOADS_DIR;
        }

        callback(null, destination);
    },

    filename: (_req: Request, file: Express.Multer.File, callback: (error: Error | null, filename: string) => void) => {
        const extension = path.extname(file.originalname);
        const fileNameWithoutExtension = path.basename(file.originalname, extension);
        const modifiedFileName = `${fileNameWithoutExtension.replace(/\s+/g, '_')}-${Date.now()}${extension}`;
        const filePath = path.join(destination.substr(PROFILE_PIC_DIR.length), modifiedFileName);
        callback(null, filePath);
    },
});

const upload = multer({
    storage,
    limits: { fileSize: 5 * 1024 * 1024 },
    fileFilter: (_req: Request, file: Express.Multer.File, callback: FileFilterCallback) => {
        const allowedMimeTypes = ['image/jpeg', 'image/png', 'image/jpg'];
        if (allowedMimeTypes.includes(file.mimetype)) {
            callback(null, true);
        } else {
            callback(new Error());
        }
    },
});

The filePath it saves in the database: Screenshot_from_2023-07-20_18-19-54-1690026281423.png

John Oliver
  • 125
  • 1
  • 11

0 Answers0