使用预览将图像上传到服务器

时间:2018-08-25 22:03:45

标签: javascript php jquery ajax

所以我有这段代码可以上传图像并显示其预览。它还允许您上传多张图像并显示其预览。

但是,我现在该如何实际将该映像推送到服务器?我已经尝试过了,但是似乎没有用。

HTML

<input type="file" name="albumPics" id="albumPics" style="display:none;" multiple="multiple" />

javascript

window.onload = function(){

    //Check File API support
    if(window.File && window.FileList && window.FileReader)
    {
        var filesInput = document.getElementById("albumPics");

        filesInput.addEventListener("change", function(event){

            var files = event.target.files; //FileList object
            var output = document.getElementById("albumPicsPreview");

            for(var i = 0; i< files.length; i++)
            {
                var file = files[i];
                alert(file);
                //Only pics
                if(!file.type.match('image'))
                  continue;

                var picReader = new FileReader();

                picReader.addEventListener("load",function(event){

                    var picFile = event.target;

                    var liContent = "<li><img style='height: 195px;' src='" + picFile.result + "'" + "title='" + picFile.name + "'/></li>";
                    $("#albumPicsPreview").prepend(liContent);
                    // output.html(div);          
                    // upload the image
                    $.ajax({
                    type: "POST",
                    url: "pettyURL.php",
                    data:  file,
                    enctype: 'multipart/form-data',
                    processData: false,  // tell jQuery not to process the data
                    contentType: false,   // tell jQuery not to set contentType
                    dataType: "json",
                    success: function(response)
                    {
                        // some code after succes from php
                        console.log("success");
                    },
                    beforeSend: function()
                    {
                        // some code before request send if required like LOADING....
                    }
                });

                }); //event listener

                 //Read the image
                picReader.readAsDataURL(file);
            }                               

        });
    }
    else
    {
        console.log("Your browser does not support File API");
    }
}

ajax在这里不起作用。似乎没有数据进入PHP文件。我该如何运作?

0 个答案:

没有答案