繁体   English   中英

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

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

客户端

我使用输入文件来获取 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>

从上面可以看出,我使用.files

我成功地用文件更新了我的反应状态:

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

服务器端

我通过获取请求 (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
            })
   })
}

但是,在服务器端,我收到了所有数据,除了附件为空:

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

首先,我知道attachments: req.body.attachments对 Nodemailer 不起作用,当我到达那里时我会穿过那座桥,哈哈。 req.body.attachments之外的所有数据?

这是控制台记录的内容:

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

我的问题是这样的:

  1. 为什么我明明通过的时候却没有收到任何文件数据?
  2. 如何正确地将文件从前端传递到服务器? 如果有更好的方法请赐教。 我见过很多不同的技术,但没有一个对我来说完全有意义。

要将文件从前端传递到服务器请从客户端使用 FormData ( https://developer.mozilla.org/en-US/docs/Web/API/FormData )。 在服务器端,我建议您使用https://www.npmjs.com/package/express-fileupload包来处理传入的文件

并且不要忘记将您的Content-Type标头设置为multipart/form-data

暂无
暂无

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

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