带有获取的React-Native上传图像

时间:2018-09-25 12:45:14

标签: reactjs react-native fetch

我正在尝试使用react-native中的fetch将图像文件发送/上传到后端服务器,但是即使尝试了不同的示例,我也无法实现任何目的。我的后端是php / laravel。我在本地使用Image Picker,效果很好。

首先,我像这样从库中获取图像;

pick(){
        ImagePicker.showImagePicker(options, (response) => {
            console.log('Response = ', response);

            if (response.didCancel) {
                console.log('User cancelled image picker');
            }
            else if (response.error) {
                console.log('ImagePicker Error: ', response.error);
            }
            else if (response.customButton) {
                console.log('User tapped custom button: ', response.customButton);
            }
            else {
                let source = { uri: response };

                // You can also display the image using data:
                // let source = { uri: 'data:image/jpeg;base64,' + response.data };

                this.uploadImage(response)
            }
        });
    }

所选图像的console.log;

{height: 332, width: 443, type: null, fileName: "YnVocPlX7yKpxrUczoySYLkKhuChMhAaIzvHlezj2VZIgwVxND…SBaBiCCszMjVNAtyy1gWQbQl6AIF7ZQ=w443-h332-nc.jpeg", fileSize: 39718, …}
data: "/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAMCAgoKCgoKCgoKCg"
fileName: "YnVocPlX7yKpxrUczoySYLkKhuChMhAaIzvHlezj2VZIgwVxNDwwSTxrKpIW6OydrR5Ll-LzH5pzqDYCJA3l5JySBaBiCCszMjVNAtyy1gWQbQl6AIF7ZQ=w443-h332-nc.jpeg"
fileSize: 39718
height: 332
isVertical: true
originalRotation: 0
path: "/storage/emulated/0/Download/YnVocPlX7yKpxrUczoySYLkKhuChMhAaIzvHlezj2VZIgwVxNDwwSTxrKpIW6OydrR5Ll-LzH5pzqDYCJA3l5JySBaBiCCszMjVNAtyy1gWQbQl6AIF7ZQ=w443-h332-nc.jpeg"
type: null
uri: "content://media/external/images/media/22"
width: 443
__proto__: Object

然后我尝试上传;

uploadImage(source){

        const data = new FormData();
        data.append('name', 'testName'); // you can append anyone.
        data.append('photo', {
            uri: source.uri,
            type: 'image/jpeg', // or photo.type
            name: 'testPhotoName'
        });

        fetch('https://xxx/react_image', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'multipart/form-data',
            },
            body: data,
        }).then((response) => response.json())
            .then((responseJson) => {

               console.log(responseJson);

            }).catch((error) => {
            //
        });
    }

我得到响应,并从后端服务器的控制台中看到它;

{name: "testName", photo: {…}}
name: "testName"
photo: {}
__proto__: Object

并且您看到的名称还可以,与我发送的名称相同,但是照片是空物体?我不知道该怎么办(在后端服务器中,我只是将请求发送回:return $ request;)。

1 个答案:

答案 0 :(得分:0)

我认为问题可能在于您正在提供图片URI,我建议尝试使用base64。您可以使用以下方法将URI转换为base64https://facebook.github.io/react-native/docs/imagestore#getbase64fortag

这是使用XMLHttpRequest的工作示例,它可能是您正在使用的fetch的替代方法:

ImageStore.getBase64ForTag(source.uri, (base64Data) => {
    var xhr = new XMLHttpRequest();
    var fd = new FormData();
    xhr.open('POST', url, true);
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

    xhr.onreadystatechange = (e) => {
        if (xhr.readyState === 4 && xhr.status === 200) {
            var response = JSON.parse(xhr.responseText);
            resolve();
        }
    };

    fd.append('file', base64Data);
    xhr.send(fd);
});

只需尝试。