5

CodeIgniter で AJAX テクノロジ (純粋な JavaScript) を使用してファイルをアップロードするメカニズムを作成しました。

説明:

1 - アップロードの AJAX/Javascript プロセスの処理を担当する script.js ファイルを作成しました。

2 - AJAX からファイルをアップロードする要求を受け取るコントローラーを CodeIgniter で作成しました。

3 - 簡単な HTML ページを作成しました

問題: アップロード ボタンを押しても何も起こりません。エラーは表示されません。javascript と php 間のデータの受け渡しに問題があると思います。通常のphpページでほぼ同様のコードを使用して成功しているためです。

ファイルは次のとおりです。

これはジャバスクリプトです

// JavaScript Document
var doUpload =  function(event){
        // globally used variables in this function
        var progressBar = document.getElementById('progressBar');

        event.preventDefault(); // prevents the default action of an element
        event.stopPropagation();        
        // get the file-input id
        var fileId = document.getElementById('file');    

        // this variable makes an object which accept key/value pairs which could be sent via ajax.send
        var formObj = new FormData();

        // append currently selected file to the dataObject            
        formObj.append('file', fileId.files[0]);        


        // this is a variable to check in the php script (controller if the codeIgniter is used)
        formObj.append('error-check', true);
        formObj.append('finish-check', true);

        // let's make the ajax request object
        var ajaxReq = new XMLHttpRequest();

        // PROGRESS  OF THE FILE /////////////////////////////////////////////
            // now trigger a function during the progress-process of the file-upload process

        ajaxReq.upload.addEventListener('progress', function(event){        

                console.log('this is a very good.');        

                // first let's get the amount of the file loaded. it is in decimals
                var percent = event.loaded / event.total;
                // get the name of the element that the progress-indicator is outputted there

                if(event.lengthComputable) // if a file is inserted and everything is just OK for uploading
                {
                    if(progressBar.hasChildNodes()) // cleans the div container for a new progress to display
                    {
                        progressBar.removeChild(progressBar.firsChild);
                    }
                    progressBar.appendChild(document.createTextNode('The Progress So Far: '+percent*100+' %'));
                }
        // END OF PROGRESS  OF THE FILE /////////////////////////////////////////////



        // LOAD  OF THE FILE /////////////////////////////////////////////
            ajaxReq.upload.addEventListener('load', function(event){
                progressBar.appendChild(document.createTextNode(" Completed!"));
            });
        // END OF LOAD  OF THE FILE /////////////////////////////////////////////

        // ERROR  OF THE FILE /////////////////////////////////////////////
            ajaxReq.upload.addEventListener('error', function(event){
                progressBar.removeChild();
                progressBar.appendChild(document.createTextNode("Failed to Upload the File."));
            });    
        // END OF THE ERROR  OF THE FILE /////////////////////////////////////////////

        // JSON            

        // OPEN THE AJAX REQUEST
        ajaxReq.open('POST', 'upload/uploader');

        // Set the header of the POST request
        ajaxReq.setRequestHeader('Cache-Control', 'no-cache');

        // send the file. remember, we shoud pass a formData object as an argument to the ajaxRequest.send();
        ajaxReq.send(formObj);

        });

}

window.addEventListener('load', function(event)
{    
        // get the submit id of the form
        var submitButton = document.getElementById('submit');
        submitButton.addEventListener('click', doUpload);
});

これは CodeIgniter の PHP コントローラーです

<?php
class Upload extends CI_Controller
{
         function index()
        {
            $this->load->view('pages/form');
         }
         function uploader ()
         {
                // define the required settings for the upload library to instanciate
                $config['upload_path'] = './uploads/';
                $config['allowed_types'] = 'gif|jpg|png|doc|txt';
                $config['max_size']  = 1024 * 8;
                $config['encrypt_name'] = TRUE;


                // load the upload library
                $this->load->library('upload', $config);


                if(!$this->upload->do_upload('file'))
                {
                    $data['error'] = $this->upload->display_errors();
                    //$this->load->view('pages/form', $data);
                    json_encode($data['error']);
                }
                else
                {
                    $data['uploaded'] = $this->upload->data();
                    //$this->load->view('pages/form', $data);    
                }


         }

}

これはHTMLです

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Upload Form With Ajax</title>
<script src="<?php echo base_url(); ?>js/script.js" type='text/javascript'></script>
</head>

<body>
<div id='error' style='color: red;height: 40px; width: 200px;'>
<?php
if(!empty($error)){echo $error; }
?>
</div>
<form id='form' name='form' enctype="multipart/form-data" >
<input type='file' name='file' id='file'/>
<input type='submit' name='submit' id='submit' value='Upload File' />
</form>
<div style='height: 200px; width: 300px; color: red; padding: 10px; background-color: #CCC;' id='progressBar'></div>
</body>
</html>
4

2 に答える 2

3

script.jsで次のように移動します。

// OPEN THE AJAX REQUEST
ajaxReq.open('POST', 'upload/uploader');
// Set the header of the POST request
ajaxReq.setRequestHeader('Cache-Control', 'no-cache')
// send the file. remember, we shoud pass a formData object as an argument to the xhruest.send();
ajaxReq.send(formObj);

progress イベントリスナーを使用しない場合:

    ajaxReq.upload.addEventListener('progress', function(event)
    {        
        console.log('this is a very good.');        
        // first let's get the amount of the file loaded. it is in decimals
        var percent = event.loaded / event.total;
        // get the name of the element that the progress-indicator is outputted there
        if(event.lengthComputable) // if a file is inserted and everything is just OK for uploading
        {
            if(progressBar.hasChildNodes()) // cleans the div container for a new progress to display
            {
                progressBar.removeChild(progressBar.firsChild);
            }
            progressBar.appendChild(document.createTextNode('The Progress So Far: '+percent*100+' %'));
        }
        // END OF PROGRESS  OF THE FILE /////////////////////////////////////////////


        // LOAD  OF THE FILE /////////////////////////////////////////////
        ajaxReq.upload.addEventListener('load', function(event)
        {
            progressBar.appendChild(document.createTextNode(" Completed!"));
        });
        // END OF LOAD  OF THE FILE /////////////////////////////////////////////
        // ERROR  OF THE FILE /////////////////////////////////////////////
        ajaxReq.upload.addEventListener('error', function(event)
        {
            progressBar.removeChild();
            progressBar.appendChild(document.createTextNode("Failed to Upload the File."));
        });    
        // END OF THE ERROR  OF THE FILE /////////////////////////////////////////////
        // JSON            
    });
    // OPEN THE AJAX REQUEST
    ajaxReq.open('POST', 'upload/uploader');
    // Set the header of the POST request
    ajaxReq.setRequestHeader('Cache-Control', 'no-cache')
    // send the file. remember, we shoud pass a formData object as an argument to the ajaxRequest.send();
    ajaxReq.send(formObj);
于 2013-07-22T00:30:45.250 に答える