Answer the question
In order to leave comments, you need to log in
How to send a file using Formdata in React to an Express server in NodeJS?
The page has a form and a button for submitting a file (using React):
const Upload = () => {
const [file, setFile] = useState();
const UploadContent = (event) => {
event.preventDefault();
if (event.target.files[0]) {
setFile(event.target.files[0]);
}
};
const OnSumbit = (event) => {
const formData = new FormData();
formData.append('customFile', file);
axios.post(
"http://localhost:3000/upload",
formData,
{
headers: {
"Content-type": "multipart/form-data"
},
}
)
.then(res => {
console.log(`Success` + res.data);
})
.catch(err => {
console.log(err);
})
}
return <div>
<h1 style={style}>Зона тестов</h1>
<input
accept="video/mp4"
id="contained-button-content"
multiple
type="file"
onChange={UploadContent}
/>
<Button variant="contained" color="primary" onClick={OnSumbit}>
Сохранить и закрыть
</Button>
</div>
app.post('/upload', function(req, res) {
let sampleFile;
let uploadPath;
if (!req.file || Object.keys(req.file).length === 0) {
return res.status(400).send('No files were uploaded.');
}
sampleFile = req.file.customFile;
uploadPath = __dirname + '/uploads/' + sampleFile.name;
customFile.mv(uploadPath, function(err) {
if (err)
return res.status(500).send(err);
res.send('File uploaded!');
});
});
Answer the question
In order to leave comments, you need to log in
The problem was in the elementary lack of folders for saving files.
To download files, multer was used and the script for the download module itself looks like this:
const path = require('path');
const multer = require('multer');
const fs = require('fs');
const filePath = {
common : './content/',
imageFile: './uploads/images/',
contentFile: './uploads/content/'
}
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path.join(__dirname, '.' + filePath[file.fieldname]))
},
filename: function (req, file, cb) {
let name = new Date().toLocaleDateString();
name = name.replace(':','-');
let result = name + '-' + file.originalname;
cb(null, (result))
}
})
exports.Remove = function (path) {
try {
fs.unlinkSync(path);
console.log('successfully deleted' + path);
} catch (err) {
console.log(err);
}
}
exports.upload = multer({storage: storage}).any();
exports.filePath = filePath;
common : './content/',
imageFile: './uploads/images/',
contentFile: './uploads/content/'
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question