React Native中使用Axios和FormData上传图片到后端的问题

问题描述 投票:0回答:1

我使用 Axios 进行后端请求来上传表单数据,包括图像。我已将图像数据包装为具有 uri、名称等属性的对象。但是,在发出请求时,响应显示图像路径和 URL 为 null,其余数据已成功上传。我无权访问后端,但在邮递员上,图像正在上传。任何人都可以提供有关如何解决此问题的指导吗?

        const data = new FormData();
        // const fileUri = Platform.OS === 'ios' ? image.replace('file://', '') : image;
        const fileExtension = getFileExtension(image) || 'jpg'; // Default extension 'jpg'
        const fileName = `imageMed.${fileExtension}`;
        data.append('file', {
            uri: image,
            name: fileName,
            type: `image/${fileExtension}`,
        });

        data.append('name', MedicineName);
        data.append('dosage', dose);
        data.append('start_time', `${Newdate} ${Newtime}`);
        data.append('number_of_days', days);
        data.append('frequency', freNumber);
        data.append('days_of_the_week', '1,2,3');
        data.append('st_notification', !isNotify ? 0 : 1);
        data.append('st_critical', !priority ? 0 : 1);
        data.append('default_icon', selectedImage);
        data.append('medicine_schedules', 'test_string');

        let config = {
            method: 'post',
            maxBodyLength: Infinity,
            url: 'https://api-patient-dev.easy-health.app/medicines',
            headers: {
                'Content-Type': 'multipart/form-data',
                'Authorization': `Bearer ${access_token}`,
            },
            data: data
        };
        console.log(data);
        axios.request(config)
            .then((response) => {
                console.log(JSON.stringify(response.data));
                renderAlarmComponents(response.data, userId);
            })
            .catch((error) => {
                console.log(error);
            })
            .finally(() => {
                setShowLoader(false);
                // navigation.navigate('Dashboard', {
                //     isChanged: true,
                // });
            });
    }
javascript react-native axios
1个回答
0
投票

将“图像”作为 URI 路径传递时会出现问题。首先,您需要验证这一点。此外,您必须确保在 iOS 和 Android 平台上正确处理文件上传。

考虑以下代码片段:

formData.append(key, { 网址: Platform.OS !== 'ios' ?文件?.uri : 文件?.uri?.replace('file://', ''), 类型:文件?.类型, 名称:文件?.文件名, });

此代码段解决了文件 URI 处理中特定于平台的差异。

如果以上未能解决您的问题,请分享数据对象的日志。

console.log(数据);

© www.soinside.com 2019 - 2024. All rights reserved.