我无法使用AJAX将数据发送到服务器

时间:2019-02-20 19:08:01

标签: javascript jquery html ajax drag-and-drop

情况如下:我将拖放图像上传到服务器。一切都会更简单,但是首先您需要将删除的图像嵌入到DOM树中,然后可以从那里将其删除,并将其余的图像发送到服务器。在放置事件中,我将文件本身和图片className添加到关联数组。在用户准备好将所有剩余图片发送到服务器之后,我将具有剩余图片类的文件添加为新数组的键,并形成新的FormData。但是服务器不接收文件。救命!

代码:

 var arr = new Map;
//create a associative array.
 dnd.addEventListener('drop', e => {
            e.preventDefault();
            var image_ = e.dataTransfer.files;

.....

  //embed dropped image into the DOM tree
const text = e.dataTransfer.getData("text");
        if (text) {

            let img = document.createElement('img');
            img.src = text;
            $('#container_').append(img);
        }
        else {

            const files = e.dataTransfer.files;
            [].map.call(files, file => {
                if (file.type.match(/^image/)) {

                    let reader = new FileReader();
                    reader.onload = file => {


                        let img = document.createElement('img');

                        img.className = "droppedPhoto" + Math.random();
                        img.setAttribute("widt", "200");
                        img.setAttribute("height", "200");
                        img.src = file.target.result;


                        let div = document.createElement('div');
                        $('#container_').append(div);
                        $('#container_').children().last().append(img);

                        arr.set(img.className, image_);

  $('.sendPhotos > p > button').on('click', function () {
        checkData(arr);

    });

    function checkData(array) {
        var $arrOfImg = $('#container_ > div > img');
        var $newArrayOfData =[]; 
        for (var i = 0; i < $arrOfImg.length; i++) {
            if (array.has($arrOfImg[i].className)) {
            $newArrayOfData.push(array.get($arrOfImg[i].className));

            }
        }
        createFormData($newArrayOfData);
    }


    function createFormData(images) {
        var formImage = new FormData();
        for (var i = 0; i < images.length; i++) {

            formImage.append(key, images[i]); 
        }

        uploadFormData(formImage);               
    }

    function uploadFormData(formData) {

        $.ajax({

            url: '@Url.Action("PhotoSessionInfo", "Home")',
            type: "POST",
            xhr: function () {
                var myXhr = $.ajaxSettings.xhr();
                return myXhr;
            },
            data: formData,
            contentType: 'multipart/form-data',
            cache: false,
            processData: false,
            success: function (response) {
                console.log("success");
                $('#container_').html(response);

            }
        });
    }

0 个答案:

没有答案