繁体   English   中英

使用 fetch api 将图像发送到 nodeJs 服务器

[英]Sending image to nodeJs server using fetch api

我正在尝试通过 fetch 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

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

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);

  }

使用此缓冲区,您可以创建图像并将其存储在服务器的文件夹中。

var fs = require('fs');

try{  
   fs.createWriteStream(path_folder_to_store_image).write(your_buffer);
   console.log('image upload');
}catch(error){
   console.log(error)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM