使用获取API将图像发送到NodeJs服务器

时间:2020-08-28 04:08:44

标签: javascript node.js fetch-api

我正在尝试通过获取API将图像发送到Nodejs服务器。客户端代码在下面

uploadByFile(file) {
    let formData = new FormData();
    formData.append("image", file);

    return fetch('/editorJS/uploads', {
        method: 'POST',
        body: formData
    })
    .then(res => res.json())
    .then(json => {
        return json;
    })
    .catch(error => console.error(error));
}

但是在服务器端,我正在获取缓冲区而不是文件。如何在那里找到文件?下面是代码

router.post('/editorJS/uploads',  (req, res) => {
    console.log(req.body);
    console.log(req.body.files);
    console.log(req.files);
}

输出为

<Buffer 2d 2d 2d 2d 2d 2d 57 65 62 4b 69 74 46 6f 72 6d 42 6f 75 6e 64 61 72 79 31 76 56 59 4d 59 4f 73 59 6a 42 67 76 5a 4b 50 0d 0a 43 6f 6e 74 65 6e 74 2d ... 10336 more bytes>
undefined
undefined

1 个答案:

答案 0 :(得分:0)

使用multer包在nodejs中获取文件,我在您下面放了一个代码。

const multer = require('multer');

const localstorage = multer.diskStorage({
    destination: function (req: any, file: any, cb: any) {
        cb(null, '');
    },

    // By default, multer removes file extensions so let's add them back
    filename: function (req: any, file: any, cb: any) {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    }
  });

  router.post('/editorJS/uploads',  multer({ storage: localstorage }).single('file')  
  (req, res) => {
   console.log(req.body);

  }
相关问题