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

时间:2018-10-17 23:54:11

标签: reactjs react-native

我尝试上传裁剪为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);
        })
}

谢谢

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

我可以使用以下插件解决它: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.
              });
相关问题