如何解决从输入下载带有 URL 的图像并将其 POST 以使用其他字段表达后端?
我正在开发一个基于 MERN 堆栈 的项目,在前端使用 Material-UI 和 React .
我有一个输入图像的 URL。单击 Submit 时需要下载图像,并将其与 POST 请求一起发送到后端,并保存在那里的目录中,同时将位置发送到 MongoDB。
请参考代码。
前端
package.json
...
"dependencies": {
...
"@material-ui/core": "^4.11.3","@material-ui/icons": "^4.11.2","react": "^17.0.2","react-dom": "^17.0.2","react-router-dom": "^5.2.0",...
},...
博客/Create.js
...
const [imageUrl,setimageUrl] = useState('');
...
const getimageFromUrl = async () => {
const response = await fetch(imageUrl);
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
return {
// using the title with the file extension as the name
originalname: `${title}.${imageUrl.split('/').pop().match(/^[\w\s-,.]+\.([a-zA-Z0-9]{3,4})/)[1]}`,buffer
};
}
handleSubmit = async (e) => {
e.preventDefault();
const form = new FormData();
form.append('title',title);
form.append('content',content);
form.append('image',getimageFromUrl());
const options = {
method: 'POST',body: form,};
const response = await fetch('http://localhost:5000/blogs',options);
const data = await response.json();
console.log(data);
// history object from useHistory();
history.goBack();
}
...
<form onSubmit={handleSubmit} enctype="multipart/form-data">
<Grid container
alignItems='center'
justify='center'
spacing={2}
>
...
<Grid item xs={12}>
<FormControl fullWidth>
<InputLabel className={classes.formlabel} htmlFor="image">Image URL</InputLabel>
<Input
id="image-url"
value={imageUrl}
className={classes.formInput}
onChange={e => setimageUrl(e.target.value)}
label="Image URL" />
</FormControl>
</Grid>
...
</Grid>
<form>
...
后端
package.json
...
"dependencies": {
...
"express": "^4.17.1","mongoose": "^5.12.0","multer": "^1.4.2",...
routes/api/blog.js
...
const router = express.Router();
const upload = multer({
storage: multer.diskStorage({
destination: (req,file,callback) => {
callback(null,'./uploads/blogs/');
},filename: (req,file.originalname);
}
}),limits: {
fileSize: 1024 * 1024 * 5
},fileFilter: (req,callback) => {
if (['image/jpg','image/png'].includes(file.mimetype)) {
callback(null,true);
} else {
callback(new Error('Image Could not be saved'));
}
}
});
// @route POST /blogs
// @description add a blog
// @access Public
router.post('/',upload.single('image'),(req,res) => {
Blog
.create({
...req.body,image: (req.file || {}).path
})
.then(data => res.json(data))
.catch(err => res.status(400).json({
error: 'Unable to add this blog',message: err.message
}));
});
...
感谢任何将图像发送到后端的帮助。
谢谢。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。