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

Flutter+PHP上传图片至SQL服务器:图片仅显示0字节问题求助

问题:Flutter图片上传至PHP后端后文件大小为0字节

我开发了一款基于Flutter的应用,采用SQL数据库存储数据,通过PHP后端将应用数据上传至SQL服务器。目前在图片上传环节遇到问题:图片显示上传完成,但文件大小仅为0字节。

实现逻辑:Flutter端将图片转换为Base64格式发送,PHP端解码后保存。


Flutter 代码

try{
  final profimage = File(image);
  final housimage = File(himage);

  String proftobase64 = base64Encode(await profimage.readAsBytes());
  String housetobase64 = base64Encode(await housimage.readAsBytes());


  String urls = api_config.sync_profile;
  var res = await http.post(Uri.parse(urls), headers: {"Accept":"application/json"},
      body:{
        "hh_id": id,
        "prof_image":proftobase64,
        ... etc.
 });
      var auth = jsonDecode(res.body);
      return auth;
}

PHP 代码

$profdir = 'Mobile-profile-img/';
$fileName = $profileCode . '.jpg';
file_put_contents($profdir.$fileName, base64_decode($profileimg));

$profimgurl = "https://e4psmap.com/Mobile-app/$profdir$fileName";

排查方向与解决办法

  • Base64编码/解码异常

    1. Flutter端先确认图片读取正常:打印await profimage.readAsBytes()的长度,确保不为0;同时查看proftobase64的开头,JPG图片的Base64通常以/9j/开头,验证格式是否正确。
    2. PHP端先检查接收的$profileimg是否完整:用var_dump(strlen($profileimg))查看长度,和Flutter发送的Base64长度对比,避免数据被截断。
    3. 处理特殊字符:Base64中的+、/等字符在POST表单提交时可能被转义,PHP端可以先执行$profileimg = urldecode($profileimg)再解码。
  • 文件路径与权限问题

    1. 确认Mobile-profile-img/目录存在且有写入权限:在PHP代码中添加var_dump(is_dir($profdir), is_writable($profdir)),两个值都返回true才正常。
    2. 检查最终文件路径:打印$profdir.$fileName确认路径无误,若目录不存在,file_put_contents会创建空文件但写入失败,导致0字节。
  • POST数据大小限制
    图片转Base64后体积会增大约30%,若超过PHP配置的post_max_size或upload_max_filesize,数据会被截断。查看php.ini文件,将这两个参数调整到足够大的值(例如post_max_size = 20M)。

  • 解码失败处理
    PHP的base64_decode失败时会返回false,此时file_put_contents会写入空内容。可以添加校验逻辑:

    $decodedImg = base64_decode($profileimg, true);
    if($decodedImg === false) {
        die('Base64解码失败');
    }
    file_put_contents($profdir.$fileName, $decodedImg);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 20:32:59