如何将图像上传到文件夹和路径ot db在cakephp控制器

时间:2017-02-10 07:21:53

标签: cakephp

我已在控制器中编写代码以将上传的文件移动到文件夹,但它无法正常工作,我的代码是

 $this->layout = "ajax";
    if($this->request->data){
    $postArr = $this->request->data;
    $a = $postArr['image'];
        $ext = substr(strtolower(strrchr($a, '.')), 1); //get the extension
                    $arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
                   if(in_array($ext, $arr_ext))
                    {
                        //do the actual uploading of the file. First arg is the tmp name, second arg is
                        //where we are putting it
                      if(move_uploaded_file($a, WWW_ROOT . '/img/uploads/users' . $a)){
                      echo 'success';
                        $hai = 1;
                      }
                      else
                      {
                      echo 'failed';
                      $hai = 0;
                      }



                    }
                    .....
                    .....

                    ......
 $Curriculum = array();
 $Curriculum['Shop']['image'] = $hai;
        $this->Shop->save($Curriculum);
         echo 0;
        exit;

我认为这行'if(move_uploaded_file($ a,WWW_ROOT。'/ img / uploads / users'。$ a)){...}无效,通过此代码,我可以存储'0在我的数据库中,也就是代码的一部分。

如何将上传的图像移动到文件夹和路径到我的数据库字段..plz帮我任何一个......!

我的脚本代码是

 function addAdminList(){
    var branchId = $('#branchId').val();
    var branchName = $('#branchName').val();
    var curiculumName = $('#curiculumName').val();
         var owner = $('#owner').val();
         var startdate = $('#startdate').val();
         var phone = $('#phone').val();
         var desc = $('#desc').val();
         var address = $('#address').val();
         var timings = $('#timings').val();
        var image = $('#image').val();                                   

    if(!$("#addClsGrpFrm").validationEngine('validate')){
        return false;
    }
    $('.overlay').show();
    $.ajax({
        url : '<?php echo BASE_PATH; ?>adminAjax/addAdminList',
        type : 'POST',
        data : {
            branchId : branchId,
            branchName : branchName,
            curiculumName : curiculumName,
            owner : owner,
            startdate : startdate,
            phone : phone,
            desc : desc,
            address : address,
            timings : timings,
            image : image
             },
        success : function(res){
            $('.overlay').hide();
            if(res == 0){

            }
            parent.$.colorbox.close();
            oTable.fnDraw();
            return false;
        },
        error : function(res){
            alert('Server Error Occurred'); 
        }
    });

}

我的表格是

    <form id="addClsGrpFrm" method="post" action="#" onsubmit="return disableFrmSubmit()">
        <div class="flash_msg"><?php echo $this->Session->flash(); ?></div>
        <input type="hidden" name="data[branch][id]" readonly id="branchId" value="0">
        <div class="login-form">
            <label>Shop Image</label>
            <input type="file" id="image" data-prompt-position="topLeft:200" name="data[branch][image]" placeholder="" class="validate[required]" />

   .....
    </div>
                <div class="login-form">
                    <input type="button" onclick="addAdminList()" class="login-btn" value="Submit">
                </div>
        <div class="clear"></div>
    </form>

2 个答案:

答案 0 :(得分:1)

提交表单时的一些建议:

  1. 在提交表单时使用 FormData ,而不是逐个添加。
  2. 您在控制器中使用的扩展提取过程可能无法使用“。”保存某些文件。在他们的文件名中。
  3. 我为您的知识创建了一个测试表。这是表格:

    <form id="testForm" method="post" action="<?php echo 'http://localhost/blog/users/test'; ?>">
        <input type="file" name="image" id="image">
        <input type="submit" value="Submit">
    </form>
    

    您可以像这样使用FormData:

    $('#testForm').on('submit', function(event) {
        event.preventDefault();
        var form_data = new FormData($(this)[0]); // this will get all your form's inputs
        $.ajax({
            url:"<?php echo 'http://localhost/blog/users/test.json'; ?>", // you can use your form action URL here
            type:'POST',
            data:form_data,
            processData: false,
            contentType: false
        });
    });
    

    最后在你的控制器中:

    public function test() {
        if ($this->request->is('post')) {
            if (!empty($this->request->data['image']['tmp_name']) && is_uploaded_file($this->request->data['image']['tmp_name'])) {
                $filename = basename($this->request->data['image']['name']); 
                $imagePath = WWW_ROOT . DS . 'documents' . DS . $filename; // save the file where you wish
                move_uploaded_file(
                    $this->request->data['image']['tmp_name'],
                    $imagePath // save $imagePath in your database
                );
            }
        }
    }
    

    您可以使用$ imagePath保存在数据库中,对于文件扩展名,您可以使用此函数,因为即使文件名中包含“点”,它也会获取文件类型:

    public function findFileTypeAndName($filename)
    {
        $split_point = '.';  
        $parts = explode($split_point, $filename);
        $last = array_pop($parts);
        $fileNameAndType = array(implode($split_point, $parts), $last);
    
        return $fileNameAndType; 
    }
    

答案 1 :(得分:0)

 $this->layout = "ajax";
    if($this->request->data){
    $postArr = $this->request->data;
    $a = $postArr['image'];
        $ext = substr(strtolower(strrchr($a['name'], '.')), 1); //get the extension
                    $arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
                   if(in_array($ext, $arr_ext))
                    {
                        //do the actual uploading of the file. First arg is the tmp name, second arg is
                        //where we are putting it
                      if(move_uploaded_file($a['tmp_name'], WWW_ROOT . '/img/uploads/users/' . basename($a['name']))){
                      echo 'success';
                        $hai = 1;
                      }
                      else
                      {
                      echo 'failed';
                      $hai = 0;
                      }



                    }
                    .....
                    .....

                    ......
 $Curriculum = array();
 $Curriculum['Shop']['image'] = $hai;
        $this->Shop->save($Curriculum);
         echo 0;
        exit;

问题只是您此时尝试将图像数组传递到strrchr($a)而不是strrchr($a['name'])

$ext = substr(strtolower(strrchr($a['name'], '.')), 1); //get the extension

然后您还尝试将$a数组传递给move_uploaded_file($a,...)。 检查我对代码部分的更正......