HTML5 drag and drop and multiple file upload

前端 未结 4 703
轮回少年
轮回少年 2021-02-06 14:53

I have an HTML form that contains a file input field with multiple file selection and I also have a drag and drop feature that I am working on as well. My question is how to int

4条回答
  •  天涯浪人
    2021-02-06 15:50

    I'm not entirely sure how you're doing it, so I'll tell you the way I do it and then try to answer your question.

    1. Set up event listeners for dropping and 's change event.
      • for dropping: filesUpload.addEventListener("change", function () {traverseFiles(this.files);}, false);
      • for : dropArea.addEventListener("drop", function (evt) {traverseFiles(evt.dataTransfer.files);}, false);
    2. traverseFiles that you see above is a function that gets a FileList (an array of Files), which are a part of the File API. This function then calls a function uploadFile for each File.
    3. uploadFile sends the File asynchronously via ajax (XMLHttpRequest.send(file)).

    Now to answer your question how to bind the dropped files to an input field: you don't, you just do it the other way. You create an API or a wrapper for uploading files and then if the user drops files, you call this wrapper function. If the user clicks on the field, you again call this wrapper (like I did with traverseFiles).

    Makes sense? If it doesn't, tell me which part and I'll edit this answer / expand on it.

提交回复
热议问题