Skip to content

Instantly share code, notes, and snippets.

@scott1028
Forked from hechien/upload_by_drag_and_drop.rb
Created December 23, 2013 11:09
Show Gist options
  • Save scott1028/8095308 to your computer and use it in GitHub Desktop.
Save scott1028/8095308 to your computer and use it in GitHub Desktop.
assets = params[:assets]
assets.each do |asset|
Asset.create(asset)
end

終於搞出來了 ... 我的媽呀,基礎知識全部忘掉就是了 ... 丟臉

Okay ... 記錄一下實作,不過怎樣用Rails建立Paperclip上傳機制這部份我就不多說了

主要是這段JavaScript code

{% gist 2937600 uploader.js %}

還有這段Rails code

{% gist 2937600 upload_by_drag_and_drop.rb %}

是的,就只有這樣,哈

正在想著把這個部分再用jQuery封裝得好看一點 ...

其實很簡單,就是JavaScript吃到drop event的時候,把收集到的檔案資訊整理起來,用FormData封裝,然後送到後台去這樣。

因為用到XMLHttpRequest,所以乾脆用jQuery來跑好了

註:drop事件、FormData似乎都是HTML 5後才有support的功能,而且不是每個Browser都有Support,所以記得還是得實作傳統的上傳機制 ...

UPDATED: 2012/06/16 02:25 --

已經更改成用jQuery的ajax來上傳了,這樣就省得再用XMLHttpRequest了

$(document).bind('drop', function(e){
e.preventDefault();
e.stopPropagation();
upload(e.originalEvent.dataTransfer.files);
}).bind('dragenter dragover', function(e){
e.preventDefault();
e.stopPropagation();
});
var upload = function(files){
if(typeof(FormData) != 'undefined'){
var form = new FormData();
form.append('path', '/');
for(i = 0; i < files.length; i++){
form.append('assets[][asset]', files[i]);
}
$.ajax({
url: '/assets/upload_by_drag_and_drop',
data: form,
type: 'POST',
contentType: false,
processData: false,
success: function(data){
console.log(data);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment