Frontend Code
package
"axios": "^0.24.0",
src/components/FileUpload
import axios from 'axios';
import React, { Fragment, useState } from 'react';
const FileUpload = () => {
const [files, setFiles] = useState([]);
const onChange = e => {
console.log(e.target.files);
setFiles(e.target.files)
};
console.log(files);
const onSubmit = async e => {
e.preventDefault();
const formData = new FormData();
Object.values(files).forEach(file=>{
formData.append("uploadImages", file);
});
try {
const res = await axios.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
});
console.log(res);
} catch (err) {
if (err.response.status === 500) {
console.log(err);
} else {
console.log(err.response.data.msg);
}
}
};
return (
<Fragment>
<form onSubmit={onSubmit}>
<div>
<input
type='file'
id='file'
name="uploadImages"
multiple
onChange={onChange}
/>
</div>
<input
type='submit'
value='Upload'
/>
</form>
</Fragment>
);
};
export default FileUpload;
src/App
import React from 'react';
import FileUpload from './components/FileUpload';
const App = () => (
<div className=''>
<FileUpload />
</div>
);
export default App;
Backend Code
package
"dependencies": {
"cors": "^2.8.5",
"express": "^4.17.1",
"multer": "^1.4.3",
"nodemon": "^2.0.15"
}
index.js
const express = require('express');
const cors = require('cors');
const path = require('path');
const multer = require('multer');
const app = express();
const port = 5000;
// app.use(express.static('uploads'))
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path.join(__dirname, './uploads'));
},
filename: function (req, file, cb) {
cb(
null,
file.fieldname + '-' + Date.now() + file.originalname.match(/\..*$/)[0],
);
},
});
const multi_upload = multer({
storage,
fileFilter: (req, file, cb) => {
if (
file.mimetype == 'image/png' ||
file.mimetype == 'image/jpeg' ||
file.mimetype == 'image/jpg'
) {
cb(null, true);
} else {
cb(null, false);
const err = new Error('Only .jpg .jpeg .png images are supported!');
err.name = 'ExtensionError';
return cb(err);
}
},
}).array('uploadImages', 10);
app.post('/api/upload', (req, res) => {
multi_upload(req, res, function (err) {
console.log(req.files);
//multer error
if (err instanceof multer.MulterError) {
console.log(err);
res
.status(500)
.send({
error: { msg: `multer uploading error: ${err.message}` },
})
.end();
return;
} else if (err) {
//unknown error
if (err.name == 'ExtensionError') {
res
.status(413)
.send({ error: { msg: `${err.message}` } })
.end();
} else {
res
.status(500)
.send({ error: { msg: `unknown uploading error: ${err.message}` } })
.end();
}
return;
}
res.status(200).send('file uploaded');
});
});
app.listen(port, () =>
console.log(`server is listening on url http://localhost:${port}`),
);
Top comments (2)
wonderfull explain