在使用以下控制器上传到 node.js 中的 Cloudinary 之前,我正在尝试使用 Jimp 调整文件服务器端的大小:
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 });
});
};
这会调整图像的大小并上传它,但是页面会刷新,这是我无法做到的。如果我注释掉await photo.write(filePath)
页面不会刷新,但是当然上传的文件不会调整大小。
前端是 React,看起来像这样:
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;
我试过了preventDefault
,但页面仍然刷新。为什么会导致页面刷新,我该如何防止它?stopPropogation
handleChange
photo.write