简体   繁体   English

如何将文件(PDF、DOC 等)从客户端(react)传递到服务器(Node - Express)

[英]How to pass a file (PDF, DOC, etc) from Client (react) to server (Node - Express)

Client side客户端

I use input file to get the PDF:我使用输入文件来获取 PDF:

 <html> <body> <input type="file" id="file_attachments" name="files" onChange=updateAttachments() multiple> </input> <script> function updateAttachments() { let files = document.getElementById("file_attachments").files; console.log('attached', files); } </script> </body>

As you can see from the above, I use .files .从上面可以看出,我使用.files

I successfully update my react states with the files:我成功地用文件更新了我的反应状态:

this.setState({
   attachments: [...files]
});

Server side服务器端

I pass the files (attachments) to my server (node) via a fetch request (POST):我通过获取请求 (POST) 将文件(附件)传递到我的服务器(节点):

onSend = () => {
   const url = config.API_ENDPOINT + "/api/email/send";

   const email = {
            to: this.state.emails,
            subject: this.state.subject,
            message: this.state.content,
            attachments: this.state.attachments
   };

   fetch(url, {
            method:"POST",
            body: JSON.stringify(email),
            headers: {
                Accept: "application/pdf",
                "Content-Type": "application/json"
   }})
   .then(res => {
            if (!res.ok) {
                res.json().then(error => {
                    throw error
                })
            }
            return res.json()
   })
   .then(data => {
            console.log('sent complete');
            console.log(data);
   })
   .catch(err => {
            this.setState({
                error: err.message
            })
   })
}

However, on the server side, I receive all the data, except attachments is empty:但是,在服务器端,我收到了所有数据,除了附件为空:

emailRouter
.route('/send')
.post(jsonParser, (req, res, next) => {
    
    console.log(req.body); //display what was received 

    let transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: 'myEmail@gmail.com', // generated ethereal user
            pass: 'xxxxxx', // generated ethereal password
          },
    });


    
    transporter.sendMail({
        from: 'myEmail@gmail.com',
        to: 'All of my Subscribers <myEmail@gmail.com>',
        bcc: req.body.to,
        subject: req.body.subject,
        html: req.body.message,
        attachments: req.body.attachments,
    }, (err, info) => {
        console.log('email sent or was there an error?');
        if (err) {
            console.log(err);
        }
        else {
            console.log('Email Sent: ', info.response);
        }
    });
});

First, I'm aware that attachments: req.body.attachments wouldn't work for Nodemailer, I'll cross that bridge when I get there lol.首先,我知道attachments: req.body.attachments对 Nodemailer 不起作用,当我到达那里时我会穿过那座桥,哈哈。 All the data received except for req.body.attachments ?req.body.attachments之外的所有数据?

This is what is logged by the console:这是控制台记录的内容:

{
  to: [email1@gmail.com, email2@yahoo.com, anotherOne@outlook.com],
  subject: 'Test email',
  message: '<p>This email was received from Nodemailer</p>\n',
  attachments: {}
}

My question is this:我的问题是这样的:

  1. Why am I not receiving any file data when I clearly passed it through?为什么我明明通过的时候却没有收到任何文件数据?
  2. How do I properly pass a file from the front end to the server?如何正确地将文件从前端传递到服务器? If there is a better way please enlighten me.如果有更好的方法请赐教。 I've seen a lot of different techniques, but none have made complete sense to me yet.我见过很多不同的技术,但没有一个对我来说完全有意义。

To pass a file from the front end to the server Please use FormData ( https://developer.mozilla.org/en-US/docs/Web/API/FormData ) from client side.要将文件从前端传递到服务器请从客户端使用 FormData ( https://developer.mozilla.org/en-US/docs/Web/API/FormData )。 And server side I would recommend you to use the https://www.npmjs.com/package/express-fileupload package to handle incoming files在服务器端,我建议您使用https://www.npmjs.com/package/express-fileupload包来处理传入的文件

And dont forget to set your Content-Type header to multipart/form-data并且不要忘记将您的Content-Type标头设置为multipart/form-data

暂无
暂无

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

相关问题 Node Express将变量从客户端传递到服务器 - Node Express pass variable from client to server 将数据从React传递到节点快递服务器 - Pass Data from React to node express server 如何从节点服务器下载文件(仅使用节点模块,不使用 express 等) - How to download a file from node server(using only node modules, no express, etc) 如何将 pdf 下载响应从 api(节点/快递)传送到客户端(反应)? - How to pipe a pdf download response from an api (node/express) to a client (react)? 如何在允许清理HTML但阻止XSS的同时将数据从Node / Express服务器传递到客户端(JavaScript)? - How to pass data from a Node/Express server to the client (JavaScript) while allowing sanitized HTML but preventing XSS? 我正在尝试将pdf文件从节点服务器下载到React Client,但是当我打开它时,它显示为空白 - I'm trying to download a pdf file from a node server to a react client but when I open it, it shows blank 如何在React-Express Node App中将对象从服务器发送到客户端组件 - How to send objects from server to client side components in react-express node app 将文档Node.js缓冲区转换为pdf文件以将其输出到客户端 - Converting a doc Node.js buffer into pdf file to output it into the client 如何允许客户端从 Node.js + Express 服务器访问任何 static 文件? - How to allow client to access any static file from Node.js + Express server? 如何在Node / Express中将JS从客户端移动到服务器? - How to Move JS from Client to Server in Node/Express?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM