我正在尝试在带有 Paperclip 的 Rails 3 应用程序中获得一些 html5 拖放功能.所以,基本上:
I'm trying to get some html5 drag-and-drop functionality in a Rails 3 app with Paperclip. So, basically:
现在,我可以让它工作的唯一方法是发送一个带有文件数据的 XMLHttpRequest 并让我的 Rails 操作读取 request.raw_post ...这不是一个可行的解决方案,因为我需要发送额外的 POST参数和真实性令牌.
Right now the only way I can get this working is by sending an XMLHttpRequest with the File data and having my Rails action read the request.raw_post ... this isn't a workable solution because I need to send along additional POST params and the authenticity token.
这是我目前所拥有的:
<!-- IN MY VIEW -->
<h2>Drag and drop upload</h2>
<div id="drop">
<h2>Drop Files Here</h2>
</div>
<script type="text/javascript" charset="utf-8">
var dropbox = document.getElementById("drop");
drop = function(evt) {
evt.stopPropagation();
evt.preventDefault();
var files = evt.dataTransfer.files;
var count = files.length;
if (count > 0) {
// handleFiles(files);
var url = '/images/raw';
var request = new XMLHttpRequest();
request.open("POST", url, true); // open asynchronous post request
request.send(files[0]);
}
}
dragEnter = function(evt) {
evt.stopPropagation();
evt.preventDefault();
}
dragExit = function(evt) {
evt.stopPropagation();
evt.preventDefault();
}
dragOver = function(evt) {
evt.stopPropagation();
evt.preventDefault();
}
// init event handlers
dropbox.addEventListener("dragenter", dragEnter, false);
dropbox.addEventListener("dragexit", dragExit, false);
dropbox.addEventListener("dragover", dragOver, false);
dropbox.addEventListener("drop", drop, false);
</script>
还有我的控制器操作:
class ImagesController < ApplicationController
# ... Normal REST actions
def raw
name = "tmp_image.png"
data = request.raw_post
@file_content = File.open("#{Rails.root.to_s}/tmp/#{name}", "wb") do |f|
f.write(data)
end
@image = Image.new(:attachment => File.new("#{Rails.root.to_s}/tmp/#{name}"))
@image.save
File.unlink("#{Rails.root.to_s}/tmp/#{name}")
render :text => 'success'
end
end
那么,使用附加参数将拖放文件发布到我的应用程序的正确方法是什么?
So, what's the proper way to POST drag-and-drop files to my app with additional params?
(如果有帮助,我将整个实验作为 这里的公共 GitHub 存储库)
(If it helps, I have the entire experiment as a public GitHub repo here)
看看
https://github.com/blueimp/jQuery-File-Upload/wiki
然后向下滚动到 Ruby(在 Rails 上).这可能正是您正在寻找的内容,包括有关如何将它与 Rails 3 和回形针一起使用的教程.根据我自己的经验,它就像一种魅力.
and scroll down to Ruby (on Rails). That probably is exactly what you are looking for, including a tutorial on how to use it with Rails 3 and paperclip. And from my own experiences it works like a charm.
正如 Joost 所说:https://github.com/yortz/carrierwave_jquery_file_upload展示了如何将carrierwave与jquery_file_upload结合的一个很好的例子
And as Joost commented: https://github.com/yortz/carrierwave_jquery_file_upload shows a nice example of how to combine carrierwave with jquery_file_upload
这篇关于如何将文件从 HTML5 拖放到 Rails 3 应用程序和回形针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!