N
N
NiceScript2019-05-20 06:59:05
Node.js
NiceScript, 2019-05-20 06:59:05

How to save file in node.js server?

I form data and send it like this

submitForm (newValue) {
 let FD = new FormData()
 FD.append('action', 'UPDATE')
 FD.append('params', JSON.stringify(OEWparams))
 if (this.oew_type === 'el_image') {
  newValue.forEach(function (item, index) {
   FD.append('p[' + index + '][0]', item.img)
   FD.append('p[' + index + '][1]', item.img_mini)
  })
 }
 for (let value of FD.values()) {
  console.log(value)
 }
 Api().post('settings', FD)
}

console
UPDATE

{"edit_type":"el","el_object":"5cad5b7f9439b91b342d3663","pixel_id":"5c7defa9f3eb9d0efcc4b5a9","el_type":"5c5e951ec3d902119834af69","value_type":"image","new_value":[],"startIndex":0}

File {uid: 1558322638902, name: "2018-lexus-lx570-116-1526419489.jpg", lastModified: 1550452912986, lastModifiedDate: Mon Feb 18 2019 11:21:52 GMT+1000 (Владивосток, стандартное время), webkitRelativePath: "", …}

File {name: "blob", lastModified: 1558322829055, lastModifiedDate: Mon May 20 2019 13:27:09 GMT+1000 (Владивосток, стандартное время), webkitRelativePath: "", size: 82204, …}

I read like this
const multer = require('multer');
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, '/tmp/my-uploads')
    },
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now())
    }
})

const upload = multer({ storage: storage }).single('p')

app.all('/settings', (req, res) => {
 var action = req.body.action;
 if (req.body.hasOwnProperty('params')) {
        if (typeof req.body.params === 'string') {
            req.body.params = JSON.parse(req.body.params);
        }
        if (req.body.params.hasOwnProperty('edit_type', 'value_type')) {
            if (req.body.params.edit_type === 'el' && req.body.params.value_type === 'image') {
                req.body.params.new_value = req.body.imgs
                upload(req, res, function (err) {
                    if (err instanceof multer.MulterError) {
                        // A Multer error occurred when uploading.
                        console.log(err)
                    } else if (err) {
                        // An unknown error occurred when uploading.
                        console.log(err)
                    }

                    // Everything went fine.
                })
            }
        }
    }		
})

But the files are not saved, what's the problem?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question