Drag & Drop File Upload

前端 未结 1 1178
臣服心动
臣服心动 2021-01-30 07:46

So I\'m struggling a bit to find what I\'m looking for and how to implement it.

I have a basic PHP file uploader working, in that a user presses a custom upload button,

1条回答
  •  野的像风
    2021-01-30 08:14

    This is absolutely realistic and possible without using any third parties plugin.

    The following snippets should give you an idea of how it could work:

    Drop area

    $(".drop-files-container").bind("drop", function(e) {
        var files = e.originalEvent.dataTransfer.files;
        processFileUpload(files); 
        // forward the file object to your ajax upload method
        return false;
    });
    

    the processFileUpload()-Method:

    function processFileUpload(droppedFiles) {
             // add your files to the regular upload form
        var uploadFormData = new FormData($("#yourregularuploadformId")[0]); 
        if(droppedFiles.length > 0) { // checks if any files were dropped
            for(var f = 0; f < droppedFiles.length; f++) { // for-loop for each file dropped
                uploadFormData.append("files[]",droppedFiles[f]);  // adding every file to the form so you could upload multiple files
            }
        }
    
     // the final ajax call
    
           $.ajax({
            url : "upload.php", // use your target
            type : "POST",
            data : uploadFormData,
            cache : false,
            contentType : false,
            processData : false,
            success : function(ret) {
                     // callback function
            }
           });
    
     }
    

    form example

    Feel free to use something like this as a starting point. The browser support of this you can find here http://caniuse.com/#feat=xhr2

    Of course you can add any extras you wish like progress bar, preview, animation...

    0 讨论(0)
提交回复
热议问题