Submit File from HttpClient Angular to API-Rest CodeIgniter 3

217 Views Asked by At

I'm trying to submit a file from Angular-CLI to API-Rest app build in Codeignite3 but the response is an unknow error.

Angular Code Service:

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 code:

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);

        }
    }

At this point I don know if it is a header setting also or I am missing something in my code. Error in the picture attached:

image description

1

There are 1 best solutions below

0
On

In the past I had a similar problem and I solved it by setting the headers:

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();
}

The solution was add header to my function_post api-rest.