代码之家  ›  专栏  ›  技术社区  ›  Razvan Zamfir

Codeigniter 3图像上传错误:图像文件名增加,但未在posts表中更新

  •  0
  • Razvan Zamfir  · 技术社区  · 7 年前

    我正在做一个基本的工作 博客应用 在Codeigniter 3.1.8和Bootstrap 4中。

    每个帖子都有一个主图像,因此,有一个 post_image 中的列 posts 桌子

    当帖子的图片被替换为 新形象 ,这就是 相同(文件)名 和旧的一样:图像文件名是递增的-mypic。jpg变成了mypic1。jpg-但是 文件名字符串 未在中更新 帖子 桌子

    代码是这样的,我相信我已经确定了问题的根源(注释):

    if(!$this->upload->do_upload()){
        $errors = array('error' => $this->upload->display_errors());
        //Keep the current image name in the posts table
        //If no new image is loaded
        $post_image = $this->input->post('postimage');
    } else {
        $data = array('upload_data' => $this->upload->data());
        // This line is the source of the problem
        $post_image = $_FILES['userfile']['name'];
    }
    

    我不知道如何正确地增加它,或者即使增加是最好的解决方案。

    问题是: 解决这个问题最可靠的方法是什么?


    编辑:

    为了保持一致性,我可能应该更新首字母(当帖子发布时) 创建 )上传代码:

    if (!$this -> upload -> do_upload()) {
        $errors = array('error' => $this -> upload -> display_errors());
        $post_image = 'default.jpg';
    } else {
        $data = array('upload_data' => $this -> upload -> data());
        $post_image = $_FILES['userfile']['name'];
    }
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Razvan Zamfir    7 年前
    // This is the check for new file is upload or not
    if ( isset($_FILES['userfile']['name']) && $_FILES['userfile']['name'] != null ) 
    {
        // Use name field in do_upload method
        if (!$this->upload->do_upload('userfile'))  {
            // If any problem in uploading
            $errors = array('error' => $this->upload->display_errors());
    
        } else {
            $data = $this->upload->data();
            // This is your new upload file name
            $post_image = $data[ 'raw_name'].$data[ 'file_ext'];
        }
    }
    else {
        // This is your old file name if user not uploading new file
        $post_image = $this->input->post('postimage');
    }
    

    希望这段代码能帮助你更新你的文件

        2
  •  0
  •   Alex    7 年前

    上载库会自动增加同名文件的数量。如果你之前上传过 my-pic.jpg 然后上传了它显示为 my-pic1.jpg 。因此,上载库会修改文件名。

    您必须通过函数获取新的文件名 $this->upload->data() 它会返回一系列与图像上传相关的项目。

    https://www.codeigniter.com/user_guide/libraries/file_uploading.html#CI_Upload::data

    你只需要更换 $post_image = $_FILES['userfile']['name']; 具有 $this->upload->data('file_name') 或者:

    $file = $this->upload->data();
    $post_image = $file['file_name']
    

    一般来说,我建议不要为文件使用任何用户提供的名称。我建议使用 $config['encrypt_name'] = true 得到一个随机的名字。上述方法也适用于此。

    推荐文章