上传图像与反应和节点没有req.files

我正在处理file upload的react / node。 我没有将文件传递到API请求,而是传递到API请求的正文部分。 我的反应代码就像,

import React, { Component } from 'react'; import request from 'superagent'; class App extends Component { constructor(props) { super(props); this.state = { image1: '', }; this.handleUploadFile = this.handleUploadFile.bind(this); this.handleSubmit = this.handleSubmit.bind(this); }; handleUploadFile = (event) => { console.log("event", event.target); this.setState({ image1: event.target.files[0], }); } handleSubmit(e) { e.preventDefault(); const dataDemo = { image: this.state.image1, }; request .post(API_URL) .set('Content-Type', 'application/json') .send(dataDemo) .end(function (err, res) { console.log("err", err); console.log("res", res); }) } render() { return ( <div> <form encType="multipart/form-data"> <div style={{width: '100%', marginTop: '10px'}}> Image 1 <input name="image1" type="file" onChange={this.handleUploadFile} /> </div> <div style={{width: '100%', marginTop: '10px'}}> <input type="submit" name="submit" value="submit" onClick={this.handleSubmit} /> </div> </form> </div> ) }` 

我想要使​​用Node / Express.js我的API代码在Node / Express中将此映像上载到服务器。

所以,请帮助我如何使用API​​上传此图像,并使用Node / Express保存到服务器(在文件夹内)。

我的节点服务器代码就像,

 router.post(END_POINT,function (req, res) { //I want to add upload code here without any third party module and without req.files/req.file. }) 

请帮帮我。 先谢谢你。

如果你正在上传多张图片,那么你可以使用req.busile和req.files

  • 您可以使用from-data邮差正文上传图像

    其中支持多个图片上传

  • 你也可以使用multipart/form-data

    var form = req.form();

    form.append('file','',{filename:'myfile.txt',

    contentType:'text / plain'

    });

您可以使用Multer发送多个图像。

 uploadImage() { const options = new RequestOptions({ headers: headers }); const inputEl: HTMLInputElement = this.el.nativeElement.querySelector('#imageField'); const fileCount: number = inputEl.files.length; const formData = new FormData(); if (fileCount > 0) { formData.append('imageField', inputEl.files.item(0)); } } 

这里imageField是input标签的名称,如下所示:

 <input type="file" name="imageField (change)="uploadImage()"> 

然后后台代码:

 exports.uploadImage = (req, res) => { var path; var storage = multer.diskStorage({ destination: function (req, res, next) { next(null, 'src/assets/images'); }, filename: function (req, file, next) { path = 'src/assets/images' + '.jpg'; next(null, req.file.originalname + '.jpg'); } }); var upload = multer({ storage: storage }).any('imageField'); upload(req, res, error=> { console.log(req.files[0].path); if(error) { return res.json(error); } res.json({ message: 'Uploaded !!', path: path }) }) }