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

Angular HttpClient向CodeIgniter3 REST API传文件遇未知错误求助

我来帮你排查这个文件上传的问题,结合你给出的Angular和CodeIgniter3代码,咱们从几个常见的核心点入手:

1. 先排查Angular侧的请求头问题

当用FormData上传文件时,Angular的HttpClient会自动生成正确的multipart/form-data请求头(包含boundary分隔符),如果手动干预这个设置反而会导致错误。你的代码里只添加了X-API-KEY是没问题的,但可以优化一下错误捕获逻辑,方便拿到更具体的报错信息:

submitImg( archivo: File, id: string ){
  const formData = new FormData();
  formData.append('file', archivo);
  
  const headers = new HttpHeaders({
    'X-API-KEY': localStorage.getItem('token') || ''
  });

  // 关键:不要手动设置Content-Type,让HttpClient自动处理
  // 加上observe: 'response'可以拿到完整的响应信息,方便调试
  return this.http.post(`${ base_api_url }/upload/do_upload/${ id}`, formData, {
    headers: headers,
    observe: 'response'
  });
}

在调用这个方法时,记得完整捕获错误细节:

this.yourImgService.submitImg(yourFile, userId).subscribe({
  next: (res) => console.log('上传成功:', res),
  error: (err) => {
    console.error('上传错误详情:', err);
    console.error('错误状态码:', err.status);
    console.error('服务端返回的错误内容:', err.error);
  }
});
2. 修正CodeIgniter3侧的几个关键问题

2.1 路径与权限问题

  • 你的upload_path用了相对路径,建议加上./避免路径解析错误,同时确保目录存在且服务器有读写权限:
  • 可以在代码里自动创建目录,防止因目录不存在导致上传失败

2.2 冗余代码与逻辑修正

  • $postData = $this->post();这行完全没用,因为文件不在POST参数里,直接删掉即可
  • 你拼接路径时用了orig_name,但实际上你已经设置了自定义file_name,应该用file_name才对

调整后的CI3代码:

public function do_upload_post() {
    $userID = $this->uri->segment(3);
    
    $config = array(
        'upload_path' => "./uploads/usuarios/profile/", // 明确相对路径
        'allowed_types' => "gif|jpg|png|jpeg",
        'max_size' => '100', // 注意这里单位是KB,如果需要更大可以调整,比如500
        'max_width' => '1024',
        'max_height' => '768',
        'file_name' => $userID . '_img_' . date('ymdhis')
    );

    // 自动创建上传目录(如果不存在)
    if (!is_dir($config['upload_path'])) {
        mkdir($config['upload_path'], 0755, true);
    }
    
    $this->load->library('upload', $config);
    
    if ($this->upload->do_upload('file')) {
        $data = array('upload_data' => $this->upload->data());
        // 用自定义的文件名拼接路径
        $path = $config['upload_path'] . $data['upload_data']['file_name'];
        $resp = array(
            'ok' => TRUE,
            'msg' => 'Imagen (' . $data["upload_data"]["file_name"] . ') subida correctamente',
        );
        $this->response($resp);
    } else {
        $error = array('error' => $this->upload->display_errors());
        $resp = array(
            'ok' => FALSE,
            'msg' => 'Error al subir imagen',
            'error' => $error
        );
        $this->response($resp, REST_Controller::HTTP_BAD_REQUEST);
    }
}
3. 额外排查点:跨域与日志
  • 如果Angular和CI3不在同一个域名下,需要在CI3的index.php开头添加CORS配置:
header("Access-Control-Allow-Origin: http://your-angular-domain.com"); // 生产环境替换成实际域名
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, X-API-KEY");

// 处理OPTIONS预检请求
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit();
}
  • 开启CI3的日志功能,在application/config/config.php里设置$config['log_threshold'] = 2;,上传相关的错误会写入application/logs目录,方便定位具体问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 16:02:59