В моем проекте я просто пытаюсь загрузить файл на мой Node-сервер из моего интерфейса React. Это простая запись на сервер, которую я использую axios для , но похоже, что данные либо не отправляются, либо не могут быть интерпретированы. Я также пытаюсь использовать express-fileupload в качестве решения, но, похоже, это не решает проблему. Вот фрагменты кода:
Реакция (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>
);
}
}
Node:
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