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?
1 Answer
Reset to default 0I have the same question as @GreenSaiko, but I also the following issues:
- I see you're overwriting
req.body
with new data. It is generally recommended that you don't modify that. - If this is all of your backend router, you're not using any kind of body parsing, so
req.body
is going to beundefined
.
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
版权声明:本文标题:node.js - Why my middleware is hanging up in nodejs? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736310591a1934433.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
console.log
s or are there any errors? – GreenSaiko Commented Nov 21, 2024 at 14:49