首页 > 解决方案 > 尝试将图像发送到 React Native 中的预签名 URL 时出现网络错误

问题描述

在我的本机项目中,我需要能够使用 axios 将图像发送到 API。为此,我具有以下功能:

    export function SetImage(image, id, token)
    {
        const formData = new FormData();
        formData.append('file',{
        uri: image.uri,
        type: image.type,
        })

        return axios({
            method: 'PUT',
            url: axios.defaults.baseURL + "/api/SetImage/"+ID,
            headers: {
                'Content-Type': 'multipart/form-data' ,
                'Authorization': 'Bearer: '+token,
            },
            data: formData
        })
    }

图像是我从ImagePicker.launchImageLibraryAsync函数中得到的返回对象,它看起来像这样:

    {
       "cancelled": false,
       "height": 2048,
       "type": "image",
       "uri": "file:///data/user/0/host.exp.exponent/cache/<PathtoSomewhere>/ImagePicker/1d408e33-b54a-4189- 
       ac66-bd86ec11069a.jpg",
       "width": 946,
      }

但是,当我尝试使用该功能时,出现以下错误,这并没有告诉我任何信息:

    Network Error
    at node_modules\axios\lib\core\createError.js:16:14 in createError
    at node_modules\axios\lib\adapters\xhr.js:84:13 in handleError
    - ... 9 more stack frames from framework internals

标签: react-nativeaxiosform-data

解决方案


我最近必须在我的项目中添加相同的功能(通过预签名的 URL 上传图像)。这个对我有用:

const uploadImage = async ({ method, url, file }: any) => {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open(method, url);
        xhr.setRequestHeader('Content-Type', file.type);
        xhr.onload = () => {
            if (xhr.status !== 200) {
                reject(
                    new Error(
                        `Request failed. Status: ${xhr.status}. Content: ${xhr.responseText
                        }`,
                    ),
                );
            }
            resolve(xhr.responseText);
        };
        xhr.send(file);
    });
};

// image === image inside local phone
export const uploadImageToUrl = async ({ image, url }: any) => {
    await uploadImage({
        method: 'PUT', url, file: {
            uri: image.uri,
            type: image.type,
        }
    });

    return { url };
};

要上传图片,您只需将其命名为:

uploadImageToUrl({ url: your-upload-url, image: your-image-object-from-image-picker })

注意:将整个图像对象传递给函数(不仅仅是 uri)

如有必要,还可以添加此行:

xhr.setRequestHeader('Authorization', 'Bearer ' + jwtoken);

推荐阅读