Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to POST files from HTML5 Drag-Drop to a Rails 3 App & Paperclip?
    text
    copied!<p>I'm trying to get some html5 drag-and-drop functionality in a Rails 3 app with Paperclip. So, basically:</p> <ol> <li>One or more files are dragged and dropped onto a DIV</li> <li>Files are POST'ed to a Rails action (together or one at a time)</li> <li>Rails action saves each files as a new attachment in Paperclip</li> </ol> <p>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. </p> <p>Here's what I have so far: </p> <pre><code>&lt;!-- IN MY VIEW --&gt; &lt;h2&gt;Drag and drop upload&lt;/h2&gt; &lt;div id="drop"&gt; &lt;h2&gt;Drop Files Here&lt;/h2&gt; &lt;/div&gt; &lt;script type="text/javascript" charset="utf-8"&gt; var dropbox = document.getElementById("drop"); drop = function(evt) { evt.stopPropagation(); evt.preventDefault(); var files = evt.dataTransfer.files; var count = files.length; if (count &gt; 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); &lt;/script&gt; </code></pre> <p>And my controller action:</p> <pre><code>class ImagesController &lt; 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 =&gt; File.new("#{Rails.root.to_s}/tmp/#{name}")) @image.save File.unlink("#{Rails.root.to_s}/tmp/#{name}") render :text =&gt; 'success' end end </code></pre> <p>So, what's the proper way to POST drag-and-drop files to my app with additional params?</p> <p>(If it helps, I have the entire experiment as a <a href="http://github.com/bigfolio/HTML5-Image-Uploading" rel="noreferrer">public GitHub repo here</a>)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload