admin管理员组

文章数量:1122832

Middleware for file upload...

// fileUpload.ts
import multiparty from 'multiparty';
import { Request, Response, NextFunction } from 'express';
import fs from 'fs';
import { InternalServerError } from '../utils/response_handlers/error_categories';

const uploadDir = 'uploads';

// Ensure the uploads directory exists
if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir, { recursive: true });
}

export function uploadFileMiddleware(req: Request, res: Response, next: NextFunction) {
    console.log('Media SERVICE: /upload route hit');

    const form = new multiparty.Form({
        uploadDir, // Directory where files will be stored
    });

    form.parse(req, (err, fields, files) => {
        if (err) {
            console.error('Error parsing form:', err);
            return next(new InternalServerError());
        }

        console.log('FIELDS:', fields);
        console.log('FILES:', files);

        // Assuming one file per field
        const uploadedFile = files.file?.[0];
        if (!uploadedFile) {
            return next(new InternalServerError('No file uploaded'));
        }

        console.log('FILE RECEIVED:');
        console.log('Original Name:', uploadedFile.originalFilename);
        console.log('MIME Type:', uploadedFile.headers['content-type']);
        console.log('File Size:', uploadedFile.size);
        console.log('Stored at:', uploadedFile.path);

        // Store the file information on the req object to pass to the next handler
        req.body.uploadedFile = uploadedFile;

        // Now, call next to proceed to the next middleware
        next();
    });
}

route where i am using it...

import express, { NextFunction, Request, Response } from "express";
import multiparty from "multiparty";
import fs from "fs";
import path from "path";
import { InternalServerError } from "../utils/response_handlers/error_categories";
import { uploadFileMiddleware } from "../middleware/upload_file";

const mediaRouter = express.Router();
const uploadDir = "uploads";

// Ensure the uploads directory exists
if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir, { recursive: true });
}

// Test route
mediaRouter.get("/test", (req, res) => {
    console.log("Media SERVICE: route hit ,,,,,,,");
    res.send("Hello World");
});

// File upload route using Multiparty
mediaRouter.post(
    "/upload",
    uploadFileMiddleware,
    async (req: Request, res: Response, next: NextFunction) => {
        try {

            const file = req.body.uploadedFile;

            console.log("File Size:", file);
            
            res.status(200).json({ message: "File uploaded successfully" });

        } catch (error) {
            next(new InternalServerError("Error uploading file" + error));
        }
    }
);

export default mediaRouter;

Now the problem is I am getting the file properly in my uploads directory but the request is not going further the middleware. What if I change the next() position outside the formparser (in the middleware) it is working but I am getting no data in the req.body.file?

Middleware for file upload...

// fileUpload.ts
import multiparty from 'multiparty';
import { Request, Response, NextFunction } from 'express';
import fs from 'fs';
import { InternalServerError } from '../utils/response_handlers/error_categories';

const uploadDir = 'uploads';

// Ensure the uploads directory exists
if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir, { recursive: true });
}

export function uploadFileMiddleware(req: Request, res: Response, next: NextFunction) {
    console.log('Media SERVICE: /upload route hit');

    const form = new multiparty.Form({
        uploadDir, // Directory where files will be stored
    });

    form.parse(req, (err, fields, files) => {
        if (err) {
            console.error('Error parsing form:', err);
            return next(new InternalServerError());
        }

        console.log('FIELDS:', fields);
        console.log('FILES:', files);

        // Assuming one file per field
        const uploadedFile = files.file?.[0];
        if (!uploadedFile) {
            return next(new InternalServerError('No file uploaded'));
        }

        console.log('FILE RECEIVED:');
        console.log('Original Name:', uploadedFile.originalFilename);
        console.log('MIME Type:', uploadedFile.headers['content-type']);
        console.log('File Size:', uploadedFile.size);
        console.log('Stored at:', uploadedFile.path);

        // Store the file information on the req object to pass to the next handler
        req.body.uploadedFile = uploadedFile;

        // Now, call next to proceed to the next middleware
        next();
    });
}

route where i am using it...

import express, { NextFunction, Request, Response } from "express";
import multiparty from "multiparty";
import fs from "fs";
import path from "path";
import { InternalServerError } from "../utils/response_handlers/error_categories";
import { uploadFileMiddleware } from "../middleware/upload_file";

const mediaRouter = express.Router();
const uploadDir = "uploads";

// Ensure the uploads directory exists
if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir, { recursive: true });
}

// Test route
mediaRouter.get("/test", (req, res) => {
    console.log("Media SERVICE: route hit ,,,,,,,");
    res.send("Hello World");
});

// File upload route using Multiparty
mediaRouter.post(
    "/upload",
    uploadFileMiddleware,
    async (req: Request, res: Response, next: NextFunction) => {
        try {

            const file = req.body.uploadedFile;

            console.log("File Size:", file);
            
            res.status(200).json({ message: "File uploaded successfully" });

        } catch (error) {
            next(new InternalServerError("Error uploading file" + error));
        }
    }
);

export default mediaRouter;

Now the problem is I am getting the file properly in my uploads directory but the request is not going further the middleware. What if I change the next() position outside the formparser (in the middleware) it is working but I am getting no data in the req.body.file?

Share Improve this question edited Nov 21, 2024 at 18:29 Brian Tompsett - 汤莱恩 5,87572 gold badges61 silver badges133 bronze badges asked Nov 21, 2024 at 13:10 Deepak SinghDeepak Singh 1 1
  • 1 Up to what line does it run? Do you see the console.logs or are there any errors? – GreenSaiko Commented Nov 21, 2024 at 14:49
Add a comment  | 

1 Answer 1

Reset to default 0

I have the same question as @GreenSaiko, but I also the following issues:

  1. I see you're overwriting req.body with new data. It is generally recommended that you don't modify that.
  2. If this is all of your backend router, you're not using any kind of body parsing, so req.body is going to be undefined.
const mediaRouter = express.Router();
mediaRouter.use(express.json())

See express.json() documentation.

Additionally, if it IS undefined, it's going to throw an error, and you're not going to catch it, because you don't have try/catch anywhere around this line:

req.body.uploadedFile = uploadedFile;

So you could silently be throwing this error:

`Cannot set property of 'uploadedFile' of undefined`

本文标签: nodejsWhy my middleware is hanging up in nodejsStack Overflow