zazvorniki
zazvorniki

Reputation: 3602

html5 drag and drop file uploads

I have a bunch of file uploads on my website and I was looking into making them into drag and drop fields. However I seem to be having an issue with them.

Is there any way to accomplish a drag and drop system without the use of javascript or plugins? I'm trying to make this as light as possible and with the least amount of code.

I have looked at several different methods of doing this such as http://html5demos.com/dnd-upload but they all include javascript.

At the moment I just have regular inputs that look like this

<input type="file" multiple="true" name="" value="" />

Upvotes: 2

Views: 5403

Answers (1)

EricP
EricP

Reputation: 3439

Afaik there is not a way to do this without the use of javascript. However, here is a simple example that does use javascript. If you drag an image over the red div it appends the image to the body. I've confirmed it works in IE11, Chrome 38, and Firefox 32. See the Html5Rocks article for a more detailed explanation.

<div id="dropZone" style="width: 100px; height: 100px; background-color: red"></div>
<script>
    var dropZone = document.getElementById('dropZone');

    // Optional.   Show the copy icon when dragging over.  Seems to only work for chrome.
    dropZone.addEventListener('dragover', function(e) {
        e.stopPropagation();
        e.preventDefault();
        e.dataTransfer.dropEffect = 'copy';
    });

    // Get file data on drop
    dropZone.addEventListener('drop', function(e) {
        e.stopPropagation();
        e.preventDefault();
        var files = e.dataTransfer.files; // Array of all files
        for (var i=0, file; file=files[i]; i++) {
            if (file.type.match(/image.*/)) {
                var reader = new FileReader();
                reader.onload = function(e2) {
                    var img = document.createElement('img');
                    img.src= e2.target.result;
                    document.body.appendChild(img);
                }
                reader.readAsDataURL(file);
    }   }   });
</script>

Upvotes: 1

Related Questions