无法使用 XHR 将 base64 格式的图像发送到 android(react-native) 中的 aws S3

Cannot send image in base64 format with XHR to aws S3 in android(react-native)

我遇到了一个非常奇怪的问题:我们的应用程序具有文档扫描功能,结果扫描给我编码的 base64 图像和照片。在 ios 平台上一切都很好,但是当我尝试在 android 上发送我的照片时,我得到 xhr.status 0 和错误。此外,下一件奇怪的事情是,当我启动调试模式并在 react-native-debugger 中启用网络检查时,图片发送时没有错误。我在安装在我的设备上的发布应用程序版本上尝试它,但仍然出现状态为 0

的错误

XHR 请求

export const uploadXHRImage = (url: string, data: IDataUploadImage) => {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    resolve('Image successfully uploaded to S3');
                } else {
                    reject(localize('failedUploadImage'));
                }
            }
        };
        xhr.ontimeout = () => reject(localize('timeoutUploadImage'));
        xhr.timeout = UPLOAD_IMAGE_TIMEOUT;
        xhr.open('PUT', url);
        xhr.setRequestHeader('Content-Type', data.type);
        xhr.send(data);
    });
};

添加到页眉:

"Content-Type": 'application/json',   
"Connection": "close",  

我找到了答案:Android 无法处理 xhr 发送的图像,同时图像未作为文件保存在缓存或其他目录中。此外,android 在数据之前需要 file://。示例在这里:

saveImage = (image: string) => {
        if (IS_IOS) {
            return `data:image/jpg;base64,${image}`;
        }

        const tempFileDirectory = `${fs.CachesDirectoryPath}`;
        const tempFilePath = `${tempFileDirectory}/${uuidv4()}.jpg`;
        fs.writeFile(tempFilePath, image, 'base64');
        return `file://${tempFilePath}`;
    };