如何在Rest API Codeigniter中上传文件

时间:2018-11-05 14:33:29

标签: rest codeigniter

我被困在codeigniter的rest api中上传文件。不断收到错误。您没有选择要上传的文件enter image description here

    $config['upload_path'] = $url.'public/images/users_pictures/';
        $config['allowed_types'] = 'jpg|jpeg|png|gif';
        $config['max_size']      = '10096000';
        $config['max_height'] = '3648';
        $config['max_width'] = '6724';
        $this->load->library('upload',$config);
        $this->upload->initialize($config);
        if($this->upload->do_upload('file'))
        {
        // $this->upload->do_upload('cover');
                $uploadData = $this->upload->data();
                $picture = $uploadData['file_name'];
        $this->db->set(array('user_image' => $picture));
        $this->db->where('user_id',$uid);
        $update = $this->db->update('asm_register');
        return $update;
        }
      else
      {
          echo $error = $this->upload->display_errors();
          return "";

      }

2 个答案:

答案 0 :(得分:1)

答案-删除Content-Type : multipart/form-data,然后将其留空。

使用api时,您必须处理文件处理。

创建了一个名为file_upload_check的方法来检查文件,您只需要传递文件输入名称作为参数即可。

<input type="file" name="file">

此处$ image_name是html标签的名称。

function file_upload_check($image_name)
{
    if (isset($_FILES[$image_name]["tmp_name"]) AND  $_FILES[$image_name]['name']!="") {
        $check_image = getimagesize($_FILES[$image_name]["tmp_name"]);
        $filename   = $_FILES[$image_name]["tmp_name"];
        $handle     = fopen($filename, "r");
        $get_name   = fread($handle, filesize($filename));

        if ($check_image == false) {
            $data['error'] = '<p class="text-danger">The file you have selected is not an image.</p>';
            $data['err'] = 1;
        }else{

            // You file upload code placed here



            $data['file_name'] = $get_name;
            $data['err'] = 0;
        }
    }else{
        $data['error'] = '<p class="text-danger">Please select a file to upload.</p>';
        $data['err'] = 1;
    }

    return $data;
}



function get_file_name()
{
    // this parameter is input file name that i am passing as a parameter.
    $fileData = $this->file_upload_check('file');

    if ($fileData['err'] == 0) {

        // Here is your file name

        $file_name = $fileData['file_name'];
    }else{
        $error = $fileData['error'];
    }
}

答案 1 :(得分:0)

请试试这个。

    if($this->upload->do_upload('file_name'))
    {
    // $this->upload->do_upload('cover');
            $uploadData = $this->upload->data();
            $picture = $uploadData['file_name'];
    $this->db->set(array('user_image' => $picture));
    $this->db->where('user_id',$uid);
    $update = $this->db->update('asm_register');
    return $update;
    }