如何解决Cloudinary上传图片不起作用反应本机和节点
我正在尝试将我的React本机应用程序中的图像上传到nodejs和cloudinary云,但是它不适用于我。那就是我的本机代码:
const App = () => {
const [profileImageSource,setProfileImageSource] = useState(require('./images/profilePic.png'));
const [imageData,setImageData] = useState("");
const [okay,setOkay] = useState(false);
const config = {
withCredentials: true,baseURL: 'http://localhost:3000/',headers: {
"Content-Type": "application/json",},};
const handleProfileImage = () => {
const options = {
title: 'Select photo',base64: true
};
ImagePicker.showImagePicker(options,(res) => {
if(res.didCancel){
}
else if(res.error){
}
else{
const image = {data: res.data};
axios
.post('/clients/upload-image',{
data: JSON.stringify({image})
},config
)
.then((res) => console.log("ok"))
.catch((err) => alert(err));
}
})
}
那是我的nodesjs代码:
require('dotenv').config();
const cloudinary = require('cloudinary').v2;
//Cloudinary configurations
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,api_key: process.env.CLOUDINARY_API_KEY,api_secret: process.env.CLOUDINARY_API_SECRET
});
app.post('/clients/upload-image',(req,res) => {
const imageStr = req.body.data;
const uploadedResponse =
cloudinary
.uploader
.upload(imageStr,{
upload_preset: 'user',})
.then((uploadedResponse) => console.log(uploadedResponse))
.catch((err) => console.log("error"));
}
我在哪里错了?我不断收到错误消息,图片没有上传到云端服务器
解决方法
您可以分享收到的错误消息吗?
另外,您是否可以确认后端正确接收了imageStr
(又名req.body.data
)? (也许在上传之前将其打印出来?)
这是一种简单的文件上传方式,使用 formidable 作为您的bodyParser,它将使您的生活变得轻松而强大,同样,现在可能会考虑使用multer,而最终取决于偏好
因此,我首先建议您在您的客户端中也使用JavaScript FormData(内置库)
- 因此,当需要将图片发送到服务器时,您将如何处理事情,如下所示:
const uploadPicture = ()=>{
const data = new FormData();
data.append('image',file)// So 'image' is the key and **file** now this is the file uploaded in user that you have in state
axios.post(url,data).then(res=>{
console.log(res)
}).catch(err=>{
console.log(err)
})
}
现在后端的处理方式
- 首先安装
npm i formidable
或yarn add formidable
- 一旦完成,您就准备好了。
const cloudinary = require('cloudinary').v2;
const Formidable = require('formidable');
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,api_key: process.env.CLOUDINARY_API_KEY,api_secret: process.env.CLOUDINARY_API_SECRET
});
router.post('/api/upload',(req,res)=>{
const form = new Formidable.IncomingForm();//Here you initialze your formidable instance
form.parse(req,(error,fields,files)=>{
const {image} = files //So due to in our request we sent a **file** which is an image then formidable parsed that request and placed file received from client in **files** that you see in callback function so now we de-structure it by key that we set in client
cloudinary.uploader.upload(image.path,{folder:'here you can specify folder you want'},(err,results)=>{
if (err) return console.log(err)
const image_url = results.secure_url
})
})
})
- 现在这样,您上传了图片
如果这对您没有意义:这是一个无耻的插件
-
去我的YouTube频道结帐我已经介绍了如何使用cloudinary
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。