我正在尝试从我的react原生应用程序上传一张图片到nodejs和cloudinary云,但这对我不起作用。这是我的react原生代码:
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"));
}我哪里错了?我一直收到错误,图片没有上传到cloudinary
发布于 2020-11-08 16:42:33
你能分享一下你收到的错误信息吗?另外,你能确认imageStr (也就是req.body.data)在后端是正确接收的吗?(也许可以在上传之前打印出来?)
发布于 2020-11-08 17:20:36
这是一个简单的文件上传和使用 formidable 作为你的bodyParser它会让你的生活变得更容易使用强大,同样的可能保证现在归结为偏好
首先,我建议您在客户机上也使用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或,这样就可以开始了。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
})
})
})如果这对您没有任何意义,请参阅:这是一个无耻的插件
https://stackoverflow.com/questions/64733898
复制相似问题