使用CodeIgniter上传ajax文件的错误处理


Error handling for ajax file uploading with CodeIgniter

使用CodeIgniter 2.1.4,我尝试使用ajax和文件上传类上传文件。我在控制器中的结构为:

public function __construct()
{
    parent::__construct();
    $this->load->helper(array('form', 'url'));
}

我在控制器中的上传功能为:

public function upload_file()
{
    $config['upload_path'] = 'upload/';
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size'] = '100';
    $config['max_width']  = '1024';
    $config['max_height']  = '768';
    $this->load->library('upload', $config);
    if (!$this->upload->do_upload())
    {
        $error = array('error' => $this->upload->display_errors());
        $result['success'] = 1;
        $result['message'] = $error;
    }
    else
    {
        $result['success'] = 0;
        $result['message'] = "Successful Upload";
    }
    die(json_encode($result));
}

但错误显示为:

Array

如何从数组中获取错误消息?

更改此行并尝试:

$result['message'] = $error['error'];

发生错误时,结果是一个数组。您在die函数中使用了json编码。

不要在die函数中进行编码。

echo json_encode($result);
die();