I am working in a reactjs application where i have to upload user image. I am getting file on onChange event of file input and passing it parent component and parent component will make a post request using the data
Server side I am using express and multer for file upload and client side using fetch api to upload the image.
Thanks in advance :)
I figure it out To upload an file/image to multer we need a form enctype="multipart/form-data" without that it wont work with multer
I am getting file from a child component then 1) i have created a empty form with the encType="mutipart/form-data" 2) when i received the file i create a new FormData(with ref to myform) 3) then append key and value in the formData 4) create fetch.post() and it works :)
for ref submitting the code
React Parent component Upload.js
import React, { Component } from 'react'
import { ImageWithoutForm } from "../app/components/ImageUpload";
export default class UploadFile extends Component {
onImageLoad(e){
console.log('onImageLoad', e.target.files[0]);
this.uploadForm(e.target.files[0]);
}
uploadForm(file){
let form = new FormData(this.refs.myForm);
form.append('myImage', file);
fetch('/upload-image', {
method: 'POST',
body: form
}).then(res => console.log('res of fetch', res));
}
render() {
return (
<div>
<h4>Upload Image</h4>
<ImageWithoutForm onImageLoad={(e)=>this.onImageLoad(e)} />
<form id="upload_form" ref="myForm" encType="multipart/form-data">
</form>
</div>
)
}
}
React Child Component with input to load the file ImageWithoutForm.js
import React, { Component } from 'react'
export class ImageWithoutForm extends Component {
handleSubmit(e){
this.props.onImageLoad(e);
}
render() {
return (
<div>
<input type="file" onChange={(e)=>this.handleSubmit(e)}/>
</div>
)
}
}
Express Route file taken from someone github repo and customized UploadImage.js
const express = require('express');
const multer = require('multer');
const path = require('path');
// Set Storage Engine
const storage = multer.diskStorage({
destination: './public/uploads/',
filename: function(req, file, cb){
cb(null,file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
// Init Upload
const upload = multer({
storage: storage,
limits:{fileSize: 1000000},
fileFilter: function(req, file, cb){
checkFileType(file, cb);
}
}).single('myImage');
// Check File Type
function checkFileType(file, cb){
// Allowed ext
const filetypes = /jpeg|jpg|png|gif/;
// Check ext
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
// Check mime
const mimetype = filetypes.test(file.mimetype);
if(mimetype && extname){
return cb(null,true);
} else {
cb('Error: Images Only!');
}
}
// Init app
const app = express.Router();
// Public Folder
app.use(express.static('./public'));
app.post('/', (req, res) => {
console.log('handling upload image');
upload(req, res, (err) => {
if(err){
console.log('first err', err);
res.send({
msg: err
});
} else {
if(req.file == undefined){
console.log('Error: No File Selected!')
res.send({
msg: 'Error: No File Selected!'
});
} else {
console.log('File Uploaded!')
res.send({
msg: 'File Uploaded!',
file: `uploads/${req.file.filename}`
});
}
}
});
});
module.exports = app;
and in my express app.js just require the route file ImageUpload.js
and map to the route like this
var uploadImage = require('./routes/UploadImage');
server.use('/upload-image', uploadImage);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With