简体   繁体   English

JQuery - 拖动删除文件 - 如何获取文件信息?

[英]JQuery - Drag n Drop Files - How to get file info?

Interested in building my own drag'n'drop file uploader using JQuery/AJAX/PHP. 有兴趣使用JQuery / AJAX / PHP构建我自己的drag'n'drop文件上传器。

Basically I want a file-uploader that users of my site can just drag the file from their computer into a div I created, and it will then upload the file for them to the selected destination. 基本上我想要一个文件上传器,我的网站用户可以将文件从他们的计算机拖到我创建的div中,然后它会将文件上传到选定的目的地。

I would like to build this from scratch, and not use any plugins so that I can better manipulate the restrictions (file types, size, destination folders, etc.) 我想从头开始构建这个,而不是使用任何插件,以便我可以更好地操纵限制(文件类型,大小,目标文件夹等)

Have scoured google with no luck, only plugins. 谷歌没有运气,只有插件。 Can anyway steer me in the right direction? 无论如何可以引导我朝着正确的方向前进?

UPDATE Ok, so I figured out how to do what I want. 更新好的,所以我想出了如何做我想要的。 Just set the file input field opacity to 1 so it is hidden, and you can still drag a file into that general area and if you hit the text field it will catch it. 只需将文件输入字段不透明度设置为1即可隐藏,您仍然可以将文件拖到该常规区域中,如果您点击文本字段,它将捕获它。 HOWEVER, I would like to know how to increase the height/width on the file input field (tried basic css on the file, but it only increases the 'browse' button size and not the actual field where you can drop the file into. Any ideas how to do this? I basically want a big square div that says 'Drop file here'. So I need to resize the input field. 但是,我想知道如何增加文件输入字段的高度/宽度(在文件上尝试了基本的css,但它只增加了'浏览'按钮的大小,而不是你可以将文件放入的实际字段。任何想法如何做到这一点?我基本上想要一个大的方形div,说'在这里删除文件'。所以我需要调整输入字段的大小。

You can use the HTML5 dragenter and dragleave events to create a dropzone. 您可以使用HTML5 dragenterdragleave事件来创建dropzone。
Then by placing a file input inside the dropzone, and hiding it with CSS, you can upload the file when the change event for the input fires, like this 然后通过在dropzone中放置一个文件输入,并用CSS隐藏它,你可以在输入的change事件触发时上传文件,就像这样

var dropzone = $("#dropzone"),
    input    = dropzone.find('input');

dropzone.on({
    dragenter : dragin,
    dragleave : dragout
});

input.on('change', drop);

function dragin(e) { //function for drag into element, just turns the bix X white
    $(dropzone).addClass('hover');
}

function dragout(e) { //function for dragging out of element                         
    $(dropzone).removeClass('hover');
}

function drop(e) {
    var file = this.files[0];
    $('#dropzone').removeClass('hover').addClass('dropped').find('img').remove();

    // upload file here
}

FIDDLE 小提琴

Just to chime in here, as I've been doing this as well the last couple of days. 只是为了在这里说话,就像我最近几天一样。 From what I understand if you're binding the drop event through jQuery you need to access that event.dataTransfer object by going through the event.originalEvent object in the event provided by jQuery. 根据我的理解,如果你通过jQuery绑定drop事件,你需要通过浏览jQuery提供的事件中的event.originalEvent对象来访问该event.dataTransfer对象。

Example: 例:

In this I bind to both the dragover as well as drop events, as this was necessary to prevent it from performing the default action (found that solution here: Prevent the default action. Working only in chrome ) 在这里我绑定dragoverdrop事件,因为这是防止它执行默认操作所必需的(在此处找到解决方案: 防止默认操作。仅在chrome中工作

$('#dropzone').bind('dragover drop', function(event) {
    event.stopPropagation(); 
    event.preventDefault();
    if (event.type == 'drop') {
        console.log(event.originalEvent.dataTransfer.files);
    }
});

Also there seems to be a bug where if you console.log() the event.dataTransfer (or event.originalEvent.dataTransfer ) it's files array is empty, it's pointed out here: event.dataTransfer.files is empty when ondrop is fired? 还有一个错误,如果你console.log() event.dataTransfer (或event.originalEvent.dataTransfer )它的文件数组是空的,这里指出: 当ondrop被触发时,event.dataTransfer.files为空?

To better answer the OPs question (I just noticed the rest of it, and I know it's old but some one might find this helpful): 为了更好地回答OP的问题(我刚刚注意到其余部分,我知道它已经过时但有些人可能会觉得这很有用):

My implementation is in jQuery, so I hope that's alright: 我的实现是在jQuery中,所以我希望没关系:

var files = [];

// Attaches to the dropzone to pickup the files dropped on it. In mine this is a div.
$("#dropzone").bind('dragover drop', function(event) {
    // Stop default actions - if you don't it will open the files in the browser
    event.stopPropagation();
    event.preventDefault();

    if (e.type == 'drop') {
        files.push(event.originalEvent.dataTransfer.files);
    }
});

// Attach this to a an input type file so it can grab files selected by the input
$("#file-input").bind('change', function(event) {
    files.push(event.target.files);
});

// This is a link or button which when clicked will do the ajax request 
// and upload the files
$("#upload-button").bind('click', function(event) {
    // Stop the default actions
    event.stopPropagation();
    event.preventDefault();

    if (files.length == 0) {
        // Handle what you want to happen if no files were in the "queue" on clicking upload
        return;
    }

    var formData = new FormData();
    $.each(files, function(key, value) {
        formData.append(key, value);
    });

    $.ajax({
        url: 'upload-ajax',
        type: 'POST',
        data: formData,
        cache: false,
        dataType: 'json',
        processData: false, // Don't process the files - I actually got this and the next from an SO post but I don't remember where
        contentType: false, // Set content type to false as jQuery will tell the server its a query string request
        success: function(data, textStatus, jqXHR) { /* Handle success */ },
        error: function(jqXHR, textStatus, errorThrown) { /* Handle error */ }
    });

});

You could also bind to the other events in the accepted answer for doing effects like making the dropzone fade in so you can see it (that's on my todo list for my library). 您还可以绑定到接受的答案中的其他事件,以执行效果,例如使dropzone淡入,以便您可以看到它(这是我的库的todo列表)。 This is the core of the actual ajax file uploading I use, however. 然而,这是我使用的实际ajax文件上传的核心。

I don't really have a convenient way to test that, but that's in essence how I did it (I essentially took all that code from the library I've been making and adapted it to fit a general code block on here in an easy to understand way). 我真的没有一种方便的方法来测试它,但这实质上就是我做的事情(我基本上从我一直在制作的库中获取了所有代码并将其调整为适合这里的通用代码块了解方式)。 Hopefully this helps some people out. 希望这可以帮助一些人。 Starting from here it was actually really easy to go ahead and add in a file queue list, with the ability to delete files from the queue, so this should be a pretty good starting point. 从这里开始实际上很容易继续并添加一个文件队列列表,能够从队列中删除文件,所以这应该是一个非常好的起点。

For those interested, I found this tutorial/demo to be helpful: http://www.viget.com/inspire/custom-file-inputs-with-a-bit-of-jquery/ 对于那些感兴趣的人,我发现这个教程/演示很有帮助: http//www.viget.com/inspire/custom-file-inputs-with-a-bit-of-jquery/

Basically uses a <span> to cover the default input field. 基本上使用<span>来覆盖默认输入字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM