I'm trying to resize a file server-side using Jimp before uploading to Cloudinary in node.js with the following controller:
exports.uploadImage = async (req, res) => {
if (!req.files) {
return res.status(400).json({ msg: 'No file to upload' });
}
const file = req.files.file;
const extension = file.mimetype.split('/')[1];
const filePath = `../client/public/images/${Date.now()}.${extension}`;
const photo = await jimp.read(file.tempFilePath);
await photo.resize(600, jimp.AUTO);
await photo.write(filePath);
cloudinary.uploader.upload(filePath, function(err, result) {
if (err) {
console.log('error', err);
}
res.json({ fileName: result.public_id });
});
};
This resizes the image and uploads it, but then the page refreshes, which I can't have. If I comment out await photo.write(filePath)
the page does not refresh, but of course then the file uploaded is not resized.
The front end is React and looks something like this:
import React from 'react';
import axios from 'axios';
handleChange = async (event) => {
const formData = new FormData();
formData.append('file', event.target.files[0]);
const res = await axios.post('http://localhost:8000/api/uploadImage', formData, {
headers: { 'Content-Type': 'multipart/form-data' }
});
this.imageRef.current.setAttribute('data-path', `${res.data.fileName}`);
}
render() {
return (
<form onSubmit={this.formSubmit}>
<div>
<label htmlFor='file-input'>
<img />
</label>
<input name="image" id='file-input' type="file" accept="image/png, image/jpeg" data-path="" ref={this.imageRef} onChange={this.handleChange} />
</div>
</form>
);
}
}
export default AddItemForm;
I tried preventDefault
and stopPropogation
on handleChange
but the page still refreshes.
Why does photo.write
cause the page to refresh and how can I prevent it?