将文件上传到nodeJS服务器

时间:2020-04-01 23:41:40

标签: javascript node.js express post fetch

客户代码:

var data = new FormData();
data.append(fileName, blob, 'test.html');

fetch('http://localhost:3000/', { 
method: 'POST',
    headers: {
    },
    body: data 
}).then(
    response => {
        console.log(response)
    }
).then(
    success => {
        console.log(success)
    }
).catch(
    error =>  {
        console.log(error)
    }
);

服务器代码:

router.post('/', urlencodedParser, function(req, res, next) {
  const body = req.body;
  console.log(body);
  res.send(`You sent: ${body} to Express`);
});

我在发帖请求的正文中发送了一个Blob。当我将其发送到服务器时,我希望服务器从请求正文中下载文件。如何下载此文件?还是有一种更简单的从客户端上传的方法?

3 个答案:

答案 0 :(得分:1)

如果您可以使用NPM软件包formidable,那么似乎可以找到一种解决方案:https://www.w3schools.com/nodejs/nodejs_uploadfiles.asp

一旦收到文件,就可以使用fs模块将其保存并存储在服务器中

答案 1 :(得分:0)

希望它可以解决您的问题。

const fs = require('fs');
let directory = '/temp/data'; // where you want to save data file

router.post('/', urlencodedParser, function(req, res, next) {
 const body = req.body;
 console.log(body);
 fs.writeFile(directory, body, function(err) {
  if(err) {
   return console.log(err);
  }
  console.log("File has been saved");
 });
 res.send(`You sent: ${body} to Express`);
});

答案 2 :(得分:0)

这解决了我的答案-https://attacomsian.com/blog/uploading-files-nodejs-express,它基本上是使用中间件来进行上传的。

这基本上是这样的:

update master
set phone = case when phone2 is null or phone2 = '' then phone3 else phone2 end
where phone is null or phone = ''

此外,我想指出一下bodyParser如何不能用于多部分数据。官方文档中提到了它,但是即使我得到的答复似乎也指向bodyParser。所以我想重申一下。

相关问题