简体   繁体   English

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

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

I got very strange issue: we have scan functionality for documents in our app and as the result scan give's me encoded base64 image with photo.我遇到了一个非常奇怪的问题:我们的应用程序中有文档扫描功能,结果扫描给了我编码的 base64 图像和照片。 Everything is good on ios platform but when I trying to send my picture on android, I get xhr.status 0 and error. ios 平台上的一切都很好,但是当我尝试在 android 上发送我的图片时,我得到 xhr.status 0 和错误。 Also, next strange thing is that when I starting debug mode and enable network inspection in react-native-debugger, picture is sending without errors.另外,下一个奇怪的事情是,当我启动调试模式并在 react-native-debugger 中启用网络检查时,图片发送时没有错误。 I was trying it on release app version, installed on my device, but still got an error with status 0我在发布应用程序版本上尝试它,安装在我的设备上,但仍然出现状态 0 的错误

XHR request 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);
    });
};

Add to header:添加到 header:

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

I found the answer: Android can not process xhr send image, while image isn't saved as file in cache or other directory.我找到了答案:Android 无法处理 xhr 发送图像,而图像未保存为缓存或其他目录中的文件。 Also, android needs file:// before data.此外,android 在数据之前需要file:// Example is here:示例在这里:

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}`;
    };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM