将文件从HttpClient Angular提交到API-Rest CodeIgniter 3

问题描述

我正在尝试将Angular-CLI中的文件提交到Codeignite3中的API-Rest应用程序构建,但是响应是一个未知错误

角度代码服务:

constructor( private http: HttpClient) { }

submitImg( archivo: File,id: string ){
    const formData = new FormData();
    formData.append('file',archivo);
    return this.http.post(`${ base_api_url }/upload/do_upload/${ id}`,formData,{
        headers: {
          'X-API-KEY': localStorage.getItem('token'),}
      });
  }

API Rest codeigniter3代码

public function do_upload_post() {
        $userID = $noticesID = $this->uri->segment(3);
        $postData = $this->post();
        $config = array(
            'upload_path' => "uploads/usuarios/profile/",//path for upload
            'allowed_types' => "gif|jpg|png|jpeg",//restrict extension
            'max_size' => '100','max_width' => '1024','max_height' => '768','file_name' => $userID . '_img_' . date('ymdhis')
        );
        $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']['orig_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' => 'Erro al subir imagen','error' => $error
            );
            $this->response($resp,REST_Controller::HTTP_BAD_REQUEST);

        }
    }

在这一点上,我不知道这是否也是标题设置,或者我的代码中缺少什么。所附图片有误:

image description

解决方法

过去,我遇到了类似的问题,我通过设置标题来解决了这个问题:

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY,Origin,X-Requested-With,Content-Type,Accept,Access-Control-Request-Method");
header("Access-Control-Allow-Methods: GET,POST,OPTIONS,PUT,DELETE");
$method = $_SERVER['REQUEST_METHOD'];
if ($method == "OPTIONS") {
   die();
}

解决方案是将标头添加到我的function_post api-rest。