如何从对象NodeJS提取FormData

时间:2020-02-24 18:31:10

标签: javascript node.js

我正在尝试将数据以及图像发送至服务器。我试图将同一函数中的所有数据添加到同一端点,因为我有一个album_id引用了数据库中的相册ID

const addData = (request, response) => {
const uuid = uuidv4(); 
let album_id;

    response.status(201).send({ message: "Success" });
     db.pool.query('INSERT INTO albums (title, date, description, id) VALUES ($1, $2, $3, $4) ON CONFLICT (id) DO NOTHING RETURNING *' , [request.body.title, request.body.date, request.body.description, uuid])
    .then(res => {
      album_id = res.rows[0].id;
      console.log('INSERT ' + res.rowCount);
      console.log(request.file)
      console.log(request.body)
    }).then(() => {
       const dbQueryPromises = [];
       for (let i = 0; i < request.body.files.length; i++) {
        dbQueryPromises.push(db.pool.query('INSERT INTO songs (id, name, link, index, album_id) VALUES ($1, $2, $3, $4, $5) ON CONFLICT (album_id, index) DO NOTHING RETURNING *', [uuidv4(), request.body.files[i].name, request.body.files[i].link, request.body.files[i].index, album_id]))
      }
        return Promise.all(dbQueryPromises);
        }).then(res => {
         console.log('Array of INSERT result for second insert');
    }).then(() => {
        db.pool.query(
        'INSERT INTO file (name, type, size, path, album_id) VALUES ($1, $2, $3, $4, $5) ON CONFLICT (album_id) DO NOTHING RETURNING *',
        [request.file.filename, request.file.mimetype, request.file.size, request.file.path, album_id]);
      }).then((res) => {
      }).catch(error => console.log(error));

}

因此,在这种情况下,我会将同一函数中的所有数据查询到同一端点,我相信我应该在一个请求中发送所有数据。

在我自己按自己的请求发送图像之前,像这样FormData {}发送图像,将图像发送到服务器正常。现在,我尝试将所有数据一起发送,如下所示:

enter image description here

它不会将图像发送到服务器,也无法访问req.file,因为它是作为FormData与其他数据对象一起发送的,而不是其本身。

所以我的问题是我该如何从该对象中提取FormData,就像它自己发送一样。

这是我将图像发送到服务器的方式

var storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'public')
    }, 
    filename: (req, file, cb) => {
        cb(null, Date.now() + '-' +file.originalname)
    }
})

var upload = multer({ storage: storage });

app.post('/albums', upload.single('file'), apiCall.addData);

0 个答案:

没有答案
相关问题