使用PHP Joomla Ajax進行文件資料表單上傳

2 月 20, 2019 | Javascript, | 0 條留言

在views/temp目錄下創建當php檔案如下分別鍵入html與Javascript jQuery Ajax部分。

建立views頁面

<?php <form action=<?php echo JUri::getInstance(); ??> id=adminForm name=adminForm enctype=multipart/form-data method=post>

      <input name="'user'" placeholder="'user'"></input><br></br>
      <input name="'password'" placeholder="'password'" type="'password'"></input><br></br>
      <input name="file/" type="file"></input>
      <button type="'submit'">Try</button>

    <script>
        (function($)
        {
            $('button').click(function(e){
                e.preventDefault();
                var form = $('form')[0];
                var formData = new FormData(form);
                $.ajax({
                    url:'index.php?option=com_hrsystem&view=training&layout=upload&format=json',
                    type : POST,
                    data : formData,
                    contentType: false,
                    cache: false,
                    processData: false,
                    success : function(data) 
                    {
                         console.log(data);

                    },error: function(data) 
                    {
                        console.log('無法送出');
                    }
                })

            });
        })(jQuery);
    </script>
?>

建立接收用的view頁面

本身應該使用controllers來建立接收頁面,但多次嘗試joomla在controllers,無法接收非json格式如FormData,在行建立另一個view給予接收。

在views/temp目錄下創建當php檔案

<?php $file = JRequest::getVar('file', null, 'files', 'array'); //接收檔案資料
    $jinput = JFactory::getApplication()-?>input;

    $dest = JPATH_SITE./files/.$file['name'];  //移動到的目錄
    move_uploaded_file($file['tmp_name'],$dest);

    $data['user']=$jinput->getString('user'); //接收的表單user資料
    $data['password']=$jinput->getString('password'); //接收的表單password資料

    $array = ['file'=>$file,'user'=>$data['user'],'password'=>$data['password']];
    $fileobj = json_encode($array);
    echo $fileobj;  //返回 json格式

?>