TAGS :Viewed: 11 - Published at: a few seconds ago

[ Ajax request saving files with Rails ]

I'm fairly new to ruby on rails and I'm trying to implment a drag and drop file feature with dnduploader.js. I'm getting the file to post to the controller, but I'm unsure how to save the file in the controller to the local file system. Here is snippets of my code if anyone can help. Thank you.

Here is the link I'm using to help me: http://onehub.com/blog/posts/designing-an-html5-drag-drop-file-uploader-using-sinatra-and-jquery-part-1/

$("#drop_target").dndUploader({
    url : "/upload",
    method : "PUT"
});

if (dataTransfer.files.length > 0) {
    $.each(dataTransfer.files, function ( i, file ) {
        var xhr    = new XMLHttpRequest();
        var upload = xhr.upload;

        xhr.open($this.data('method') || 'POST', $this.data('url'), true);
        xhr.setRequestHeader('X-Filename', file.fileName);

        xhr.send(file);
    });
};

This is where I don't know what to do? I see the upload request happening inside chrome, but I'm unsure how to get the file saved to the filesystem.

def upload
  render :text => "uploaded #{env['HTTP_X_FILENAME']} - #{request.body.read.size} bytes -- #{params[:upload].to_yaml}"
end

Answer 1


It seems that the file is uploaded as "request.body". So you can do something like the following:

fp = File.open("/local_path/local_file", "wb") 
fp.write(request.body.read) 
fp.close