Yêu cầu thg 10 18, 2021 12:03 SA 177 0 1
  • 177 0 1
+1

Cách ghi nhiều file ảnh sử dụng multer vào mongodb. Nhờ các cao nhân giải quyết vấn đề nho nhỏ này cho e với.

Chia sẻ
  • 177 0 1

Bài toán là em có 2 field, 1 field là để tải 1 ảnh vào Database và 1 field là để tải nhiều ảnh vào Database. Nhưng hiện tại chỉ ghi được 1 field tải 1 ảnh còn field tải nhiều ảnh thì ko ghi được, khả năng là do sai cú pháp.

Định nghĩa 2 fields 'image' và 'imageslibrary' sử dụng multer và gọi trong router

const FieldsUpload = upload.fields([{ name: 'image', maxCount: 1 },{ name: 'imageslibrary', maxCount: 10 }])
router.post('/products/create',FieldsUpload,ProductController.postcreate)

Đây là docs của multer. Dòng 7 có vẻ như là để ghi 1 array vào Database

1. const cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
2. app.post('/cool-profile', cpUpload, function (req, res, next) {
3. // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
4. //
5. // e.g.
6. //  req.files['avatar'][0] -> File
7. //  req.files['gallery'] -> Array
8. //
9. // req.body will contain the text fields, if there were any
10.})

Ghi 2 trường theo docs của multer vào MongoDB trong controller. Nhưng chỉ có trường req.files['image][0] là nhận dữ liệu vì chỉ có 1 ảnh. Còn req.files['imageslibrary'] thì ko nhận.

Products.create({
       parent:req.body.parent, 
       parentslug:req.body.parentslug,
       name:req.body.name.trim(),
       slug:req.body.slug,
       productprice:req.body.productprice,  
       productindex:req.body.productindex, 


       image:req.files['image'][0].path.split('\\').slice(2).join('\\').replace(/\\/,'/'),
       imageslibrary:req.files.['imageslibrary'].path,
            

       description:req.body.description,
      status:req.body.status,
      new:req.body.new,
      special:req.body.special
})

Các bác chỉnh hộ e cú pháp để ghi được trường nhiều ảnh vào Database với.

1 CÂU TRẢ LỜI


Đã trả lời thg 10 18, 2021 3:54 SA
+2

hi @ThiDinh

Mình nghĩ bạn bị sai syntax chổ

imageslibrary:req.files.['imageslibrary'].path,

Bạn thử update lại thành

imageslibrary:req.files['imageslibrary'].path,

Khi lấy một thuộc tính của object có 2 cách, một là dùng dấu chấm trực tiếp còn 2 là dùng string as attribute, k thể dùng cả 2 cùng lúc. Nhưng mình thắc mắc sao IDE k báo lỗi nhỉ

Chia sẻ
Avatar Thi Đình @ThiDinh
thg 10 26, 2021 4:10 SA

ok thank bác đã quan tâm, e đã tìm ra đó là vì nó là 1 mảng object [{},{},{}] nên ko thể .path trực tiếp được. Mình phải tách trường path ra trước.