在我的项目中,我只是试图从我的React前端上传文件到我的Node服务器。这是我使用axios的服务器的简单帖子,但似乎数据要么没有被发送,要么无法被解释。我也试图使用express-fileupload作为解决方案,但它似乎没有解决问题。以下是代码段:
React(App.js)
var URLs = {
imgUpload: 'http://127.0.0.1:8003/imgUpload'
};
class App extends Component {
...
uploadHandler = () => {
console.log('handling upload...')
if (this.state.activeFile == null) {
alert('Please Select an Image!!');
} else {
let af = this.state.activeFile;
console.log('active file: ' + JSON.stringify(af))
let data = new FormData();
data.append('file', af);
data.append('name', af.name);
console.log('attempting to post: ' + JSON.stringify(data))
axios.post(URLs.imgUpload, data, {
headers: { 'Content-Type': 'multipart/form-data' }
}
)
}
}
addFile = (event: any): void => {
let activeFile = event.target.files[0];
console.log('Added file ' + activeFile);
this.setState ({
activeFile: activeFile,
});
}
render() {
return (
<div className="App">
...
<FormGroup>
<ControlLabel htmlFor="fileUpload" style={{ cursor: "pointer" }}><h3><Label bsStyle="success">Add file</Label></h3>
<FormControl
id="fileUpload"
type="file"
// accept=".pdf"
onChange={this.addFile}
style={{ display: "none" }}
/>
<Button bsStyle="success" onClick={this.uploadHandler}>Upload</Button>
</ControlLabel>
</FormGroup>
</div>
);
}
}
节点
const fileUpload = require('express-fileupload');
var express = require('express')
var app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
...
app.post('/imgUpload', function(req, res) {
let img = req;
console.log('attempting to upload image, searching for data...')
console.log('Files: ' + req.files)
var body = "";
req.on('data', function (data) {
body += data;
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
if (body.length > 1e6) {
// FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
req.connection.destroy();
}
});
});
网站控制台:
节点控制台:
attempting to upload image, searching for data...
Files: undefined