weixin_33739523 2015-04-22 10:49 采纳率: 0%
浏览 6

AJAX上传网络应用

I need some assistance please.

I am trying to create an ajax upload web app from scratch as a personal hobby. I was able to get the files to upload to my uploads folder successfully, but I just can't seem to get the uploaded links to appear under the upload box and stay there permanently even after refreshing the web page.

I keep getting this error message in the google chrome browser console:
Uncaught TypeError: Cannot read property 'length' of undefined

and it is pointing me to this line in the index.php:
for(x = 0; x < data.succeeded.length; x = x + 1) {

Also the google chrome console is marking this as (anonymous function) in the upload.js file:
o.options.finished(uploaded);

I had used some youtube videos as a guide, but I just can't seem to figure it out.

Kindly Help Me Please

This is the index.php code and below is the upload.php code also the upload.js code.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Uploader</title>
        <link rel="stylesheet" href="css/global.css">
    </head>
    <body>
        <form action="upload.php" method="post" enctype="multipart/form-data" id="upload" class="upload">
            <fieldset>
                <legend>Upload files</legend>
                <input type="file" id="file" name="file[]" required multiple>
                <input type="submit" id="submit" name="submit" value="Upload">
            </fieldset>

            <div class="bar">
                <span class="bar-fill" id="pb"><span class="bar-fill-text" id="pt"></span></span>       
            </div>

            <div id="uploads" class="uploads">
                Uploaded file links will appear here.           
            </div>

            <script src="js/upload.js"></script>
            <script>

                document.getElementById('submit').addEventListener('click', function(e) {
                    e.preventDefault();

                    var f = document.getElementById('file'),
                        pb = document.getElementById('pb'),
                        pt = document.getElementById('pt');

                    app.uploader({
                        files: f,
                        progressBar: pb,
                        progressText: pt,
                        processor: 'upload.php',

                        finished: function(data) {
                            var uploads = document.getElementById('uploads'),
                                succeeded = document.createElement('div'),
                                failed = document.createElement('div'),

                                anchor,
                                span,
                                x;

                            if(data.failed.length) {
                                failed.innerHTML = '<p>Unfortunately, the following failed:</p>';
                            }

                            uploads.innerText = '';

                            for(x = 0; x < data.succeeded.length; x = x + 1) {
                                anchor = document.createElement('a');
                                anchor.href = 'uploads/' + data.succeeded[x].file;
                                anchor.innerText = data.succeeded[x].name;
                                anchor.target = '_blank';

                                succeeded.appendChild(anchor);
                            }

                            for(x = 0; x < data.failed.length; x = x + 1 ) {
                                span = document.createElement('span');
                                span.innerText = data.failed[x].name;

                                failed.appendChild(span);
                            }

                            uploads.appendChild(succeeded);
                            upload.appendChild(failed);

                        },

                        error: function() {
                            console.log('Not working');
                        }
                    });
                });             
            </script>

        </form>
    </body>
</html>

Upload.php code

<?php
header('Content-Type: application/json');

$uploaded = '';
$allowed = '';

$succedeed = '';
$failed = '';

if(!empty($_FILES['file'])) {
    foreach($_FILES['file']['name'] as $key => $name) {
        if($_FILES['file']['error'][$key] === 0) {

            $temp = $_FILES['file']['tmp_name'][$key];

            $ext = explode('.', $name);
            $ext = strtolower(end($ext));

            $file = md5_file($temp) . time() . '.' . $ext;          

                if(move_uploaded_file($temp, "uploads/{$file}") === true) {
                    $succedeed[] = array(
                        'name' => $name,
                        'file' => $file
                    );
                } else {
                    $failed[] = array(
                        'name' => $name
                    );
                }               
        }
    }

    if(!empty($_POST['ajax'])) {
        echo json_encode(array(
        'succedeed' => $succedeed,
        'failed' => $failed
    ));
    }   
}

This is the upload.js code

var app = app || {};

(function(o) {
    "use strict";

    //Private methods
    var ajax, getFormData, setProgress;

    ajax = function(data) {
        var xmlhttp = new XMLHttpRequest(), uploaded;

        xmlhttp.addEventListener('readystatechange', function() {
            if(this.readyState === 4) {
                if(this.status === 200) {
                        uploaded = JSON.parse(this.response);

                        if(typeof o.options.finished === 'function') {
                        o.options.finished(uploaded);
                    }
                } else {
                    if(typeof o.options.error === 'function') {
                        o.options.error();
                    }
                }               
            }
        });

        xmlhttp.upload.addEventListener('progress', function(event) {
            var percent;

            if(event.lengthComputable === true) {
                percent = Math.round((event.loaded / event.total) * 100);
                setProgress(percent);
            }
        });

        xmlhttp.open('post', o.options.processor);
        xmlhttp.send(data);
    };

    getFormData = function(source) {
        var data = new FormData(), i;

        for(i = 0; i < source.length; i = i + 1) {
            data.append('file[]', source[i]);
        }

        data.append('ajax', true);

        return data;
    };

    setProgress = function(value) {
        if(o.options.progressBar !== undefined) {
            o.options.progressBar.style.width = value ? value + '%' : 0;
        }

        if(o.options.progressText !== undefined) {
            o.options.progressText.innerText = value ? value + '%' : '';
        }
    };

    o.uploader = function(options) {
        o.options = options;

        if(o.options.files !== undefined) {
            ajax(getFormData(o.options.files.files));
        }
    }

}(app));
  • 写回答

1条回答 默认 最新

  • Lotus@ 2015-04-22 11:49
    关注

    I think the problem is due to if(move_uploaded_file($temp, "uploads/{$file}") === true) try if(move_uploaded_file($temp, "uploads/{$file}") == true)

    and also check data.succedeed spell in index.php

    评论

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题