You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native与PHP图片上传异常:Postman正常App报JSON解析错误求助

解决React Native图片上传PHP后端JSON解析错误

问题描述

使用React Native上传图片到PHP后端API时,出现如下错误:

SyntaxError: JSON Parse error: Unexpected end of input

Postman测试接口可正常运行,但App调用时触发该错误。

修复方案

1. 调整React Native端请求代码

核心问题是手动设置Content-Type导致表单边界符丢失,以及Android平台URI格式兼容问题:

修改后的代码:

import { Platform } from 'react-native';

uploadImageToServer = () => {
    const data = new FormData();
    // 适配Android URI格式,移除file://前缀
    const fileUri = Platform.OS === 'android' 
        ? this.state.uri.replace('file://', '') 
        : this.state.uri;

    data.append('image', {
        name: this.state.name,
        type: this.state.type,
        uri: fileUri,
    });

    fetch('https://tmbsbavan.com/api/family_method.php', {
        method: 'POST',
        // 移除手动设置的Content-Type,fetch会自动生成带边界符的正确头
        body: data,
    })
    .then(async (response) => {
        // 调试时可先打印原始响应文本,排查后端返回内容
        // const text = await response.text();
        // console.log('后端原始响应:', text);
        return response.json();
    })
    .then((json) => {
        console.log(json);
    })
    .catch((err) => {
        console.log('请求错误:', err);
    });
}

关键修改说明:

  • 移除手动设置的'Content-Type': 'multipart/form-data':fetch会根据FormData自动生成包含边界分隔符的Content-Type,手动设置会覆盖该值,导致后端无法解析表单数据。
  • 适配Android URI:部分Android设备需要移除file://前缀才能让FormData正确识别文件。

2. 完善PHP后端错误处理

原PHP代码仅在上传成功时返回JSON,失败时无任何输出,导致前端解析空内容报错。需补充全场景错误处理,确保无论成功失败都返回合法JSON:

修改后的代码:

<?php
$response = [];
$targetDir = "../profile_pic/";

// 确保目标目录存在,不存在则递归创建
if (!is_dir($targetDir)) {
    mkdir($targetDir, 0755, true);
}

$targetFile = $targetDir . rand() . "_" . time() . ".jpeg";

// 检查文件上传状态
if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
    if (move_uploaded_file($_FILES['image']['tmp_name'], $targetFile)) {
        $response['status'] = 'success';
        $response['message'] = "Image Uploaded Successfully.";
    } else {
        $response['status'] = 'error';
        $response['message'] = "Failed to save uploaded file.";
    }
} else {
    $response['status'] = 'error';
    $response['message'] = "No file uploaded or upload error occurred.";
    // 可选:返回错误码用于调试
    if (isset($_FILES['image'])) {
        $response['error_code'] = $_FILES['image']['error'];
    }
}

// 设置响应头为JSON格式
header('Content-Type: application/json');
echo json_encode($response);
?>

关键修改说明:

  • 新增目录检查:确保上传目录存在,避免move_uploaded_file因目录不存在失败。
  • 全场景错误捕获:覆盖文件不存在、上传错误、保存失败等所有场景,均返回JSON格式响应。
  • 明确响应头:设置Content-Type: application/json,让前端明确知道响应格式。

内容的提问来源于stack exchange,提问作者Rilesh Patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 13:35:22