Reputation: 211
Hi I need to upload file in react which will be save in UI side in react
folder.
for that I have written index.js
to save the file in folder.
const express = require('express');
const app = express();
const multer = require('multer');
const cors = require('cors');
// setup multer for file upload
var storage = multer.diskStorage({
destination: './build',
filename: function (req, file, cb) {
cb(null, file.originalname);
},
});
app.use(
cors({
origin: '*',
})
);
const upload = multer({ storage: storage });
app.use(express.json());
// serving front end build files
app.use(express.static(__dirname + '/../build'));
// route for file upload
app.post(
'localhost:80/api/uploadfile',
upload.single('myFile'),
(req, res, next) => {
console.log('FIle uploaded successfully');
console.log(req.file.originalname + ' file successfully uploaded !!');
res.sendStatus(200);
}
);
app.listen(80, () => console.log('Listening on port 80'));
and my react ui
app is.
import axios from 'axios';
import React, { Component } from 'react';
class FileUpload extends Component {
state = {
selectedFile: null,
};
onFileChange = (event) => {
this.setState({ selectedFile: event.target.files[0] });
};
onFileUpload = () => {
const formData = new FormData();
formData.append('myFile', this.state.selectedFile);
console.log(this.state.selectedFile);
axios.post('http://localhost:80/api/uploadfile', formData, {
headers: {
'content-type': 'multipart/form-data',
},
}); //I need to change this line
};
fileData = () => {
if (this.state.selectedFile) {
return (
<div>
<h2>File Details:</h2>
<p>File Name: {this.state.selectedFile.name}</p>
<p>File Type: {this.state.selectedFile.type}</p>
<p>
Last Modified:{' '}
{this.state.selectedFile.lastModifiedDate.toDateString()}
</p>
</div>
);
} else {
return (
<div>
<br />
<h4>Choose before Pressing the Upload button</h4>
</div>
);
}
};
render() {
return (
<div>
<h1>Plese select the translation file</h1>
<div>
<input type="file" onChange={this.onFileChange} />
<button onClick={this.onFileUpload}>Upload!</button>
</div>
{this.fileData()}
</div>
);
}
}
export default FileUpload;
my index.js
and react app
both are running on port 80
. and my start script in package.json
is
"start":dotenv -e .env -- webpack-dev-server --hot --define process.env.dev --inline --port 80 --host localhost
When I am saving file from UI then below error is coming
Can you guide me what mistake I am doing.
Upvotes: 0
Views: 827
Reputation: 146
FYI: You can get better information for debugging an API if you use the Network
tab on the devtools, then you can inspect the specific request.
My assumption is that the first parameter you're passing to app.post
is badly formatted. Instead of localhost:80/api/uploadfile
it should be /api/uploadfile
. You can read more about it here.
You should check the parameter you're passing to axios.post
too. You just need to pass /api/uploadfile
, as you can see on this official example.
Upvotes: 1