ajax上传图片

Posted 三贞九烈

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ajax上传图片相关的知识,希望对你有一定的参考价值。

 

                            html代码

<body>
    <script type="text/javascript" src="./jquery-1.8.3.min.js"></script>
    <div class="wrap">
        <button id="upload">点击上传文件</button>
        <div>
            <p id="before"></p>
            <p id="process"></p>
            <div id="fileWrap">
                <p>上传文件列表</p>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        var button  = document.getElementById(‘upload‘),
            before  = document.getElementById("before"),
            process = document.getElementById("process");

        $(document).on(‘click‘, ‘button‘, function(){
            upload({
                url: ‘./upload.php‘,
                maxSize: 2,
                multiple: true,
                beforeSend: function(file){
                    before.innerText = "开始上传...";
                },
                callback: function(data){
                    data = JSON.parse(data);
                    if(data && data.code == 200){
                        before.innerText = "上传成功!"
                    }else{
                        console.log(data.data);
                    }
                    var fileWrap  = document.getElementById(‘fileWrap‘);
                    for(var i=0; i<data.data.length; i++){
                        var p = document.createElement(‘p‘);
                        var file = document.createElement(‘a‘);
                        file.href = ‘//practice.jumoshen.cn/ajax-file-upload//‘ + data.data[i].file_path;
                        file.target = "_blank"
                        file.innerText = "文件名:" + data.data[i].file_path;
                        p.appendChild(file);
                        fileWrap.appendChild(p);
                    }
                },
                uploading: function(pre){
                    process.innerText = "当前上传进度为:" + pre + "%";
                }
            });
        }) 
    </script>
</body>

                js代码

function upload(option){
    var formData = new FormData(),
    xmlHttpRequest = new XMLHttpRequest()
    input = document.createElement(‘input‘);
    input.setAttribute(‘id‘, ‘myUploadInput‘);
    input.setAttribute(‘type‘, ‘file‘);
    input.setAttribute(‘name‘, ‘file‘);
    if(option.multiple){
        input.setAttribute(‘multiple‘, true);
    }
    document.body.appendChild(input);
    input.style.display = ‘none‘;

    input.click();
    var fileType = [‘doc‘,‘docx‘,‘xls‘,‘xlsx‘,‘pdf‘,‘jpg‘,‘png‘,‘ppt‘,‘pptx‘];
    input.onchange = function(){
        if(!input.value){return;}
        console.log(input.value)
        var type = input.value.split(‘.‘).pop();
        if(fileType.indexOf(type.toLocaleLowerCase()) == -1){
            alert("暂不支持该类型的文件,请重新选择!");
            return;
        }
        for(var i=0, file; file=input.files[i++];){
            if(option.maxSize &&  file.size > option.maxSize * 1024 * 1024){
                alert(‘请上传小于‘+option.maxSize+‘M的文件‘);
                return;
            }
        }
        if(option.beforeSend instanceof Function){
            if(option.beforeSend(input) === false){
                return false;
            }
        }
        for(var i=0, file; file=input.files[i++];){
            console.log(formData)
            formData.append(‘file‘+i, file);
        }
        xmlHttpRequest.open(‘post‘, option.url);
        xmlHttpRequest.onreadystatechange = function(){
            if(xmlHttpRequest.status == 200){
                if(xmlHttpRequest.readyState == 4){
                    if(option.callback instanceof Function){
                        option.callback(xmlHttpRequest.responseText);
                    }
                }
            }else{
                alert("上传失败!");
            }
        }
        xmlHttpRequest.upload.onprogress = function(event){
            var pre = Math.floor(100 * event.loaded / event.total);
            if(option.uploading instanceof Function){
                option.uploading(pre);
            }
        }
        xmlHttpRequest.send(formData);
    }
}

 

  php代码

<?php
    if(!empty($_FILES)){
        $files = $_FILES;
        $length = count($files);
        $returnData = array();
        $returnData[‘code‘] = 200;
        for ($i = 1; $i <= $length; $i++) { 
            $tmpName = ‘file‘.$i;
            if (!empty($files[$tmpName])) {
                $ext = next((explode(‘.‘, $files[$tmpName][‘name‘])));
                $fileName = ‘./images/‘.time().rand().‘.‘.$ext;
                if(move_uploaded_file($files[$tmpName][‘tmp_name‘], $fileName)){
                    $returnData[‘data‘][$i-1][‘message‘]   = ‘第‘.$i.‘张图片上传成功!‘;
                    $returnData[‘data‘][$i-1][‘file_path‘] = $fileName;
                }else{
                    $returnData[‘data‘][$i-1][‘message‘]   = ‘第‘.$i.‘张图片上传失败!‘;
                    $returnData[‘data‘][$i-1][‘file_path‘] = null;
                    $returnData[‘code‘] = 0;
                }
            }
        }
    }else{
        header(‘location: http://www.jumoshen.cn‘);
    }

    echo json_encode($returnData);

以上是关于ajax上传图片的主要内容,如果未能解决你的问题,请参考以下文章

jQuery / ajax 上传图片并保存到文件夹

Ajax实现异步上传图片

ajax上传图片

纯Ajax上传图片到服务器端

ajax异步上传图片&SpringMVC后台代码

Ajax 上传图片