Javascript DataTransfer项目无法通过异步调用持久保存

时间:2019-04-12 20:15:28

标签: javascript vuejs2

我正在使用Vuejs和DataTransfer异步上传文件,并且我希望允许拖放多个文件一次上传。

我可以进行第一次上载,但是到完成上载时,Javascript已垃圾回收或更改了DataTransfer items对象。

我该如何重做(或克隆event / DataTransfer对象),以便在整个ajax调用中仍然可以使用数据?

我一直在MDN文档上了解如何使用DataTransfer,但是我很难将其应用于我的特定情况。正如您在我的代码中所看到的那样,我还尝试了复制事件对象,但显然并没有进行深层复制,只是传递了引用,这没有帮助。

    methods: {
        dropHandler: function (event) {
            if (event.dataTransfer.items) {
                let i = 0;
                let self = this;
                let ev = event;

                function uploadHandler() {
                    let items = ev.dataTransfer.items;
                    let len = items.length;

                    // len NOW EQUALS 4

                    console.log("LEN: ", len);
                    if (items[i].kind === 'file') {
                        var file = items[i].getAsFile();
                        $('#id_file_name').val(file.name);
                        var file_form = $('#fileform2').get(0);
                        var form_data = new FormData(file_form); 

                        if (form_data) {
                            form_data.append('file', file);
                            form_data.append('type', self.type);
                        }

                        $('#file_progress_' + self.type).show();
                        var post_url = '/blah/blah/add/' + self.object_id + '/'; 
                        $.ajax({
                            url: post_url,
                            type: 'POST',
                            data: form_data,
                            contentType: false,
                            processData: false,
                            xhr: function () {
                                var xhr = $.ajaxSettings.xhr();
                                if (xhr.upload) {
                                    xhr.upload.addEventListener('progress', function (event) {
                                        var percent = 0;
                                        var position = event.loaded || event.position;
                                        var total = event.total;
                                        if (event.lengthComputable) {
                                            percent = Math.ceil(position / total * 100);
                                            $('#file_progress_' + self.type).val(percent);
                                        }
                                    }, true);
                                }
                                return xhr;
                            }
                        }).done((response) => {
                                i++;
                                if (i < len) {

                                    // BY NOW, LEN = 0.  ????

                                    uploadHandler();
                                } else {
                                    self.populate_file_lists();
                                }
                            }
                        );
                    }
                }

                uploadHandler();
            }
        },

3 个答案:

答案 0 :(得分:5)

调用await后,您将不再位于该函数的原始调用堆栈中。这在事件侦听器中尤其重要。

我们可以使用setTimeout复制相同的效果:

dropZone.addEventListener('drop', async (e) => {
  e.preventDefault();
  console.log(e.dataTransfer.items);
  setTimeout(()=> {
    console.log(e.dataTransfer.items);
  })
});

例如,拖动四个文件将输出:

DataTransferItemList {0: DataTransferItem, 1: DataTransferItem, 2: DataTransferItem, 3: DataTransferItem, length: 4}  
DataTransferItemList {length: 0}

事件发生后,状态已更改,项目已丢失

有两种方法可以解决此问题:

  • 复制项目并遍历它们
  • 将异步作业(Promises)放入数组中,稍后使用Promise.all
  • 处理它们

第二个解决方案比在循环中使用await更直观。另外,请考虑parallel connections are limited。使用数组,您可以创建块来限制同时上传。

function pointlessDelay() {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, 1000);
  });
}

const dropZone = document.querySelector('.dropZone');

dropZone.addEventListener('dragover', (e) => {
  e.preventDefault();
});

dropZone.addEventListener('drop', async (e) => {
  e.preventDefault();
  console.log(e.dataTransfer.items);
  const queue = [];
  
  for (const item of e.dataTransfer.items) {
    console.log('next loop');
    const entry = item.webkitGetAsEntry();
    console.log({item, entry});
    queue.push(pointlessDelay().then(x=> console.log(`${entry.name} uploaded`)));
  }
  
  await Promise.all(queue);
});
body {
  font-family: sans-serif;
}

.dropZone {
  display: inline-flex;
  background: #3498db;
  color: #ecf0f1;
  border: 0.3em dashed #ecf0f1;
  border-radius: 0.3em;
  padding: 5em;
  font-size: 1.2em;
}
<div class="dropZone">
  Drop Zone
</div>

答案 1 :(得分:2)

随着时间的流逝,似乎缺少DataTransfer上下文。我的解决方案是在丢失所需数据之前复制所需数据,并在需要时重新使用它:

const files = [...e.dataTransfer.items].map(item => item.getAsFile());

使用我的解决方案修改了jsfiddle@Brad中的代码:

const dropZone = document.querySelector(".dropZone");
const sendFile = file => {
  const formData = new FormData();
  for (const name in file) {
    formData.append(name, file[name]);
  }
  /**
   * https://docs.postman-echo.com/ - postman mock server
   * https://cors-anywhere.herokuapp.com/ - CORS proxy server
   **/
  return fetch(
    "https://cors-anywhere.herokuapp.com/https://postman-echo.com/post",
    {
      method: "POST",
      body: formData
    }
  );
};

dropZone.addEventListener("dragover", e => {
  e.preventDefault();
});

dropZone.addEventListener("drop", async e => {
  e.preventDefault();
  const files = [...e.dataTransfer.items].map(item => item.getAsFile());
  const responses = [];

  for (const file of files) {
    const res = await sendFile(file);
    responses.push(res);
  }
  console.log(responses);
});
body {
  font-family: sans-serif;
}

.dropZone {
  display: inline-flex;
  background: #3498db;
  color: #ecf0f1;
  border: 0.3em dashed #ecf0f1;
  border-radius: 0.3em;
  padding: 5em;
  font-size: 1.2em;
}
<div class="dropZone">
  Drop Zone
</div>

答案 2 :(得分:0)

我遇到了这个问题,并试图保留整个DataTransfer对象,而不仅仅是itemstypes,因为我的异步代码的API使用了DataTransfer自行输入。我最终要做的是创建一个new DataTransfer(),并有效地复制原始属性(拖动图像除外)。

以下是要点(在TypeScript中):https://gist.github.com/mitchellirvin/261d82bbf09d5fdee41715fa2622d4a6

// https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItem/kind
enum DataTransferItemKind {
  FILE = "file",
  STRING = "string",
}

/**
 * Returns a properly deep-cloned object of type DataTransfer. This is necessary because dataTransfer items are lost
 * in asynchronous calls. See https://stackoverflow.com/questions/55658851/javascript-datatransfer-items-not-persisting-through-async-calls
 * for more details.
 * 
 * @param original the DataTransfer to deep clone
 */
export function cloneDataTransfer(original: DataTransfer): DataTransfer {
  const cloned = new DataTransfer();
  cloned.dropEffect = original.dropEffect;
  cloned.effectAllowed = original.effectAllowed;

  const originalItems = original.items;
  let i = 0;
  let originalItem = originalItems[i];
  while (originalItem != null) {
    switch (originalItem.kind) {
      case DataTransferItemKind.FILE:
        const file = originalItem.getAsFile();
        if (file != null) {
          cloned.items.add(file);
        }
        break;
      case DataTransferItemKind.STRING:
        cloned.setData(originalItem.type, original.getData(originalItem.type));
        break;
      default:
        console.error("Unrecognized DataTransferItem.kind: ", originalItem.kind);
        break;
    }

    i++;
    originalItem = originalItems[i];
  }
  return cloned;
}

您可以像这样使用它,然后以最初计划使用clone的相同方式使用evt.dataTransfer

const clone = cloneDataTransfer(evt.dataTransfer);