thắc mắc Lỗi khi dùng Multer trong Nodejs

talatroi

Senior Member
Hi ae,:beat_brick: nhờ ae tí, project này mình Node + typescript nên hơi rắc rối tí, mình maintain lại nên ko biết gì, ae giúp nhé:pudency: vấnđề duy nhất là Image Upload nha ae,đó giờ mình ko dùng kiểu này nên ko biết sai ở đâu~~
Code ở Controller.ts
JavaScript:
export const CreateConsultingData = async (req: Request, res: Response) => {
  const {
    // parent_page_id
    name,
    place,
   
    contents,
    attachment,
  } = req.body;
  const parent_page_id = process.env.PRONG_PAGE;
  const file_nm = req.file
  ? config.MULTER_TYPE === "local"
    ? req.file.filename
    : req.file.key
  : undefined;
const file_org_nm = req.file ? req.file.originalname : undefined;
const file_url = req.file
  ? config.MULTER_TYPE === "local"
    ? "/file/" + file_nm
    : req.file.location
  : undefined;
  try {
  
   
    if (!parent_page_id || parent_page_id.length !== 24) {
      return res
        .status(400)
        .send(
          new FailedMessage(
            MessageCode.CMS_COMMON_00001.error_code,
            "parent_page_id값이 유효하지 않습니다."
          )
        );
    }
    const isValidParam = CheckPageParam(req.body);
    if (!isValidParam) {
      return res
        .status(400)
        .send(
          new FailedMessage(
            MessageCode.CMS_COMMON_00001.error_code,
            MessageCode.CMS_COMMON_00001.description
          )
        );
    }
    await TransactionWrap(async (session) => {
      const response = await ProngDB.CreateConsultingData(
        {
          parent_page_id,
          name,
          place,
          file_nm, file_org_nm, file_url,
          contents,
          attachment,
        },
        { session }
      );
      if (response) {
        return res.send(new SuccessMessage(response));
      } else {
        return res
          .status(400)
          .send(
            new FailedMessage(
              MessageCode.CMS_DATA_00001.error_code,
              MessageCode.CMS_DATA_00001.description
            )
          );
      }
    });
  } catch (e) {
    console.log(e);
    res.status(500).send(new InternalErrorMessage());
  }
  console.log(req.file);
  console.log(req.body);
};

Code ở model.ts // mình thử dùng

JavaScript:
export interface ProngModel {
  _id?: ObjectId;
  // parent_page_id: ObjectId;
  page?: {
    // name of the project you want to create
    name: string;
    place: string;
    attachment: File;
    //slug
    file_nm:string; file_org_nm:string; file_url:string;
    //Time created
    //start day
    //place
    contents: string;
    //sumary about what going on
    // small title
    //number of page
    //notice or desc of the action
  };
  delete_at: boolean;
  regist_dt: Date;
  update_dt?: Date;
  delete_dt?: Date;
}

* Data in Model

JavaScript:
export const CreateConsultingData = async (
  param: {
    parent_page_id: string;
    name: string;
    file_nm:string; file_org_nm:string; file_url:string;
    //slug
    // slug: string;
    place: string;
    //Time created
    // createdAt: string;

    contents: string;
    attachment: File;
    //sumary about what going on
    // title: string;
    // small title
    // descriptionSmallTitle: string;
    //breadscrum defination
    // breadScrum: string;

    //number of page
    // paginationPage: number;

    //notice or desc of the action
    // Notification: number;
  },
  options?: { session?: ClientSession }
) => {
  const prongColl = await DataCommonDB.GetDataCollection(param.parent_page_id);
  if (!prongColl) {
    return null;
  }

  const {
    name,
    place,
    file_nm, file_org_nm, file_url,
    contents,
    attachment,
  } = param;

  const notice: ProngModel = {
    // parent_page_id: new ObjectId(parent_page_id),
    page: {
      name,
      place,
      file_nm, file_org_nm, file_url,
      contents,
      attachment,
    },
    delete_at: false,
    regist_dt: new Date(),
    update_dt: new Date(),
  };

  const response = await prongColl.insertOne(notice, { ...options });

  if (response) {
    return {
      ...notice,
      _id: response.insertedId,
    };
  } else {
    return null;
  }
};
mình nghĩ tất cả các phần khác ok hết, khi mình dùng postman
20211a9ad3be-0641-456e-ae92-d82971088930.png

mình console body + file ra thì
2021870d31db-0f01-4c95-b3a1-67828ffba4c6.png


mình ko thấy sai ở đâu cả, nhờ ae giúp với, chiều nộp rồi:beat_plaster:
 
Last edited:
lỗi rõ ràng thế mà, client gửi lên 1 field là attachment, nhưng server ko expect field đó.
Sửa lại code để tất cả các field trong form, ở cả 2 phía client + server đều giống nhau là đc
 
lỗi rõ ràng thế mà, client gửi lên 1 field là attachment, nhưng server ko expect field đó.
Sửa lại code để tất cả các field trong form, ở cả 2 phía client + server đều giống nhau là đc
ý bác là cái filed "attachment" đúng ko? mình vừa check lần nữa, ko thiếu, bác chịu khó check giúp mình với ko thấy sai ở đâu hết :beat_plaster:
 
Thím up thêm code route middleware của của multer lên đi, cái này là lỗi chỗ multer middleware r
như vầy nè thím, lead yêu cầu ko rõ, gửi multer sẽ có 2 option là local và gửi lên AWS S3, tất cả code liên quan đều setup hết. :pudency:
Lead yêu cầu có 2 thứ mình define ở model là:
1. Là "attachment" mình define là: File, nhưng có 3 param cần chú ý là:
JavaScript:
file_nm:string;

 file_org_nm:string;

 file_url:string
=>cả 3 là tên file, url.... mình nghĩ ko biết 3 param này có liên quan gì đến "attachment" ko? nên mình ko define ở model vì cả 3 là conifg của multer. :sweat:
2. Là "file_path": mình nghĩ cái này dùng để upload url từ file middleware, vậy "attachment" dùng làm gì?
Đây là cái routes mình define + middleware:
JavaScript:
const multer = require(config.MULTER_TYPE === 'local' ? '../../../../../middlewares/multer' : '../../../../../middlewares/multerS3');
router.post("/consulting",multer.uploadSingle('file_path', BUCKET_FOLDER.COMPANY_LOGO), controller.CreateConsultingData);
Đây là query của mình, mình nghĩ là sai cmnr :beat_plaster:
2021fe2800be-b528-4ed2-af26-fa1736c3271f.png

Nhờ thím!!!
 
Back
Top