AJAX JQuery файл загрузки не работает

0

Я использую jQuery ajax для загрузки файлов. Когда я нажимал кнопку загрузки, он терпит неудачу, и в разделе ошибок ajax отображается сообщение " Uncaught TypeError: Cannot read property 'length' of undefined. Я проверил код и обнаружил, что alerting the jqXHR shows success in the first ajax call,but the ajax call in submitForm() is not working. Контроллер останавливается перед $.each(event,data) и показывает $.each(event,data) выше ошибку в консоли. Пожалуйста, помогите мне.

Мой код ниже:

$(document).ready(function()
{ 
    //for checking whether the file queue contain files or not
    var files;
    // Add events
    $('input[type=file]').on('change', prepareUpload);

    // Grab the files 
    function prepareUpload(event)
    {
        files = event.target.files;
        alert(files);
    }
    $("#file-form").on('submit',uploadFiles);
    function uploadFiles(event)
    {
        event.stopPropagation();  
        event.preventDefault(); 

        // Create a formdata object and add the files
        var data = new FormData();
        $.each(files, function(key, value)
        {
            data.append(key, value);
            //alert(key+' '+ value);
        });
        $.ajax({
            url: 'module/portal/filesharing/upload.php?files',
            type: 'POST',
            data: data,
            cache: false,
            dataType: 'json',
            processData: false, 
            contentType: false, 
            success: function(data, textStatus, jqXHR)
            {
                if(typeof data.error === 'undefined')
                {
                    // Success so call function to process the form
                    submitForm(event, data);
                }
                else
                {
                    console.log('ERRORS: ' + data.error);
                }
            }
        });
        function submitForm(event, data)
        {
            // Create a jQuery object 
            $form = $(event.target);

            // Serialize the form data
            var formData = $form.serialize();//controller stops here

            // sterilise the file names
            $.each(data.files, function(key, value)
            {
                formData = formData + '&filenames[]=' + value;
            });

            $.ajax({
                url: 'update.php',
                type: 'POST',
                data: formData,
                cache: false,
                dataType: 'json',
                success: function(data, textStatus, jqXHR)
                {
                    if(typeof data.error === 'undefined')
                    {
                        // Success so call function to process the form
                        console.log('SUCCESS: ' + data.success);
                    }
                    else
                    {
                        // Handle errors here
                        console.log('ERRORS: ' + data.error);
                    }
                },
                error: function(jqXHR, textStatus, errorThrown)
                {
                    // Handle errors here
                    console.log('ERRORS: ' + textStatus);
                },
                complete: function()
                {
                    // STOP LOADING SPINNER
                }
            });
        }
    }  
});    
</script>

Html:

<form id='file-form' action="" method="post" enctype="multipart/form-data"> 
    <input type="file" name="file" id="filename" ><br>
    <input type="submit"  id='upload' value="Upload file">
</form>

Мой update.php:

$data = array();
if(isset($_GET['files']))
{    
    $error = false;
    $files = array();
    $uploaddir = 'module/portal/filesharing/upload/';
    foreach($_FILES as $file)
    {
        if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
        {
            $files[] = $uploaddir .$file['name'];
        }
        else
        {
            $error = true;
        }
    }
    $data = ($error) ? array('error' => 'There was an error uploading your files') :     array('files' => $files);
}
else
{
    $data = array('success' => 'Form was submitted', 'formData' => $_POST);
}

echo json_encode($data);
Теги:
file-upload

1 ответ

0

Если вы хотите, чтобы он работал в кросс-браузере, я рекомендую вам использовать iframe, как это http://www.ajaxf1.com/tutorial/ajax-file-upload-tutorial.html

Или есть некоторые модули jquery, использующие flash для загрузки, они также являются хорошим вариантом для более старой версии Internet Explorer

Возможно, ваша проблема заключается в этом, пожалуйста, проверьте это, как получить загруженный путь изображения в php и ajax?

Ещё вопросы

Сообщество Overcoder
Наверх
Меню