在响应本机 API 请求中上传 base64 图像



我尝试上传裁剪为 600,400 的 base64 图像,当我发出请求时,它会告诉我意外的令牌">",但是当我从裁剪为 20,20 的图像上传时,API 调用有效。所以这是base64的长度问题,似乎我不能大我也尝试编码,但也大了600,400。所以我不得不辞职发送一个小图像,或者有另一种方式。

这是我的图像代码:

ImagePicker.openPicker({
width: 600,
height: 400,
cropping: true,
includeBase64: true
}).then(image => {
uploadPictureVar = 'data:image/jpeg;base64,' + image.data;
window.picture = uploadPictureVar;
this.setState({ uploadPicture: uploadPictureVar });
});

这是我的 api 调用

export function uploadPost(post) {
let data = {
body: post.body,
picture: post.picture,
type: post.type,
user: {
_id: post.user._id,
name: post.user.name,
picture: post.user.picture
}
}
var headers = {
'Content-Type': 'application/json',
'Access-Control-Origin': '*'
}
return fetch(URL + "/uploadPost", {
method: "post",
headers: headers,
body: JSON.stringify(data)
})
.then(response => Promise.resolve(response.json()))
.catch(err => {
return Promise.reject(err);
})
}

谢谢

是否可以使用 Chrome 检查器查看您从服务器返回的响应。也许后端正在抛出错误并呈现 HTML 页面,因此错误......意想不到的"<"。我猜您正在尝试解析 JSON,但您得到了 HTML 响应。

我可以使用这个插件解决它:https://github.com/bamlab/react-native-image-resizer

这是我的代码:

ImageResizer.createResizedImage(window.picture, 600, 400, "PNG", 100, 0, null).then((response) => {
alert(response)
bodySendNewPost.picture = response.uri;
// response.uri is the URI of the new image that can now be displayed, uploaded...
// response.path is the path of the new image
// response.name is the name of the new image with the extension
// response.size is the size of the new image
}).catch((err) => {
alert(err)
// Oops, something went wrong. Check that the filename is correct and
// inspect err to get more details.
});

最新更新