我很难用本机拍摄照片,并将缓存映像发送到我的node.js后端服务器,然后我的后端服务器将其附加到一个formdata对象并将其发送到我的webservice。我搜索了很多关于前端和后端之间的操作,但没有找到确切的真实答案。
我的快速节点后端服务器用multer获取图像。
我有如下所示的反应本机前端代码,以便将作为expo的takePictureAsync方法返回对象的图像数据发送出去:
客户端
//react native client side
const takePicture = async () => {
if (cameraRef.current) {
const options = { quality: 0.5, base64: true, skipProcessing: true };
const data = await cameraRef.current.takePictureAsync(options);
const source = data.uri;
if (source) {
await cameraRef.current.pausePreview();
setIsPreview(true);
uploadFile(source);
console.log('picture source', source);
}
}
};然后,当我尝试用axios将这些图像数据发送到我的node.js后端服务器时,我从后端得到404状态错误:
//react native client side
async function uploadFile(photo) {
const formData = new FormData();
formData.append('file', {
uri: photo,
name: 'test',
mimetype: 'image/jpeg',
});
await axios
.post('http://MyLocalIpAdress:3000/photo-upload', formData, {
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
})
.then((res) => {
console.log(res.data);
return res.data;
});
}服务器端
我的Node.js后端端点如下:
router.post(
'/photo-upload',
multer({ storage: multer.memoryStorage() }).single('file'),
async (req, res) => {
if (req.file) {
try {
// Transfers uploaded image through webservice
const form = new FormData();
form.append('file', req.file.buffer, {
contentType: req.file.mimetype,
filename: req.file.originalname,
});
res.status(200).send({
message: 'Success'
});
} catch (err) {
res.status(500).send({
message: `Could not upload the file: ${req.file.originalname}. ${err}`,
});
}
} else {
return res.status(400).send({ message: 'Please upload a file!' });
}
})我不知道我是在服务器端还是客户端做错了什么,以及做错了什么。
发布于 2022-01-11 17:23:41
在使用formData将图像数据发送到后端时,我也遇到了同样的问题。有几个技巧可以解决这个问题:
解决方案1:
const formdata = new FormData();
formdata.append('image[]', {
name: 'test',
type: imageurl?.type,
uri:
Platform.OS !== 'android'
? 'file://' + photo
: photo,
});
const res = await axios.post('http://MyLocalIpAdress:3000/photo-upload', formdata, {
headers: {
Accept: '*/*',
'Content-type': 'multipart/form-data',
},
});解决方案2:(我个人选择)是使用一个库上传数据。rn-获取-blob是我用来解决这个问题的东西。如果您计划使用这一点,请仔细阅读文档并实现它。
RNFetchBlob.fetch('POST', 'http://MyLocalIpAdress:3000/photo-upload',
{
Authorization : "Bearer access-token",
'Content-Type' : 'multipart/form-data',
}, [
// element with property `filename` will be transformed into `file` in form data
{ name : 'avatar', filename : 'avatar.png', data: binaryDataInBase64},
// custom content type
{ name : 'avatar-png', filename : 'avatar-png.png', type:'image/png', data: binaryDataInBase64},
// part file from storage
{ name : 'avatar-foo', filename : 'avatar-foo.png', type:'image/foo', data: RNFetchBlob.wrap(path_to_a_file)},
// elements without property `filename` will be sent as plain text
{ name : 'name', data : 'user'},
{ name : 'info', data : JSON.stringify({
mail : 'example@example.com',
tel : '12345678'
})},
]).then((resp) => {
// ...
}).catch((err) => {
// ...
})https://stackoverflow.com/questions/70670215
复制相似问题