将Codeigniter图片上传到服务器文件夹

时间:2018-09-16 14:51:57

标签: php ajax image codeigniter upload

我是图像上传的新手,并想寻求有关将文件图像上传到服务器文件夹的帮助。 我正在使用ajax将图像发送到控制器。这是我在var_dump中将其接收到的内容。 调用$ _FILES ['croppedImage']之后 我得到的结果是

array(5) { ["name"]=> string(4) "blob" ["type"]=> string(10) "image/jpeg" 
["tmp_name"]=> string(14) "/tmp/phpqtmMQu" ["error"]=> int(0) ["size"]=> 
int(10686) }

这是我的控制器功能,用于将图像上传到服务器文件夹中。

  public function upload_base_64(){

    $MY_UPLOAD_DIR = "alert_images/";

    $imagefilename = basename( $_FILES['croppedImage']['name']);

    $fulluploadpath =base_url().'/uploads/'.$MY_UPLOAD_DIR. $imagefilename;
    $image_name = strip_tags($_FILES['croppedImage']['name']);
    $image_size = getimagesize($_FILES['croppedImage']['tmp_name']);

    if($image_size == FALSE) {
        echo 'The image was not uploaded';
    } 
    else if(move_uploaded_file($_FILES['croppedImage']['tmp_name'], $fulluploadpath )) {
        var_dump('it works');exit;

    } else {
        echo "Sorry, there was a problem uploading your file.";
    }
}

它进入了else条件。我看到了一些包含此代码的教程,但我不知道如何使用它,为什么它只需要名称?不需要文件吗?

    public function uploadfeaturedfile()
   {
    $dir_name                   = 'alert_images/';
    $config['upload_path']      = './uploads/'.$dir_name;
    $config['allowed_types']    = 'gif|jpg|png|jpeg';
    $config['max_size']         = '5120';
    $config['min_width']        = '640';
    $config['min_height']       = '640';

    $this->load->library('dbcupload', $config);
    $this->dbcupload->display_errors('', '');

    if($this->dbcupload->do_upload('photoimg'))
    {
        $data = $this->dbcupload->data();
        $this->load->helper('date');

        $format = 'DATE_RFC822';
        $time = time();
        create_rectangle_thumb('./uploads/'.$dir_name.$data['file_name'],'./uploads/thumbs/');

        $media['media_name']        = $data['file_name'];
        $media['media_url']         = base_url().'uploads/'.$dir_name.$data['file_name'];
        $media['create_time']       = standard_date($format, $time);
        $media['status']            = 1;

        $status['error']    = 0;
        $status['name'] = $data['file_name'];
    }else{
        $errors = $this->dbcupload->display_errors();
        $errors = str_replace('<p>','',$errors);
        $errors = str_replace('</p>','',$errors);
        $status = array('error'=>$errors,'name'=>'');
    }
    echo json_encode($status);
    die;
}  

我们非常感谢所有帮助!!!请先谢谢。

1 个答案:

答案 0 :(得分:0)

从文档上看,这几乎是逐字记录:

    $config['upload_path'] = './uploads/alert_images/'; // folders have to exist
    $config['allowed_types'] = 'gif|jpg|png';
    $this->load->library('upload', $config);
    if (!$this->upload->do_upload('blob')) {
        show_error($this->upload->display_errors());
    } else {
        print_r($this->upload->data());
    }

https://www.codeigniter.com/userguide3/libraries/file_uploading.html

我怀疑您的代码无法正常工作,因为您需要一个正确的(相对)文件路径(不能使用url);这里的更多内容:https://www.coffeecup.com/help/articles/absolute-vs-relative-pathslinks/