Skip to content

Instantly share code, notes, and snippets.

@spq24
Created February 20, 2013 23:47
Show Gist options
  • Save spq24/5000772 to your computer and use it in GitHub Desktop.
Save spq24/5000772 to your computer and use it in GitHub Desktop.
jquery-file-upload-rails not working
Model:
class Pin < ActiveRecord::Base
attr_accessible :description, :image
validates :description, presence: true, length: { :maximum => 140 }
validates :user_id, presence: true
validates_attachment :image, presence: true,
content_type: { content_type: ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'] },
size: { less_than: 5.megabytes }
belongs_to :user
has_attached_file :image, styles: { medium: "320x240>"}
def to_jq_upload
{
"name" => read_attribute(:image_file_name),
"size" => read_attribute(:image_file_size),
"url" => upload.url(:original),
"delete_url" => image_path(self),
"delete_type" => "DELETE"
}
end
end
Controller:
class PinsController < ApplicationController
before_filter :authenticate_user!, except: [:index]
# GET /pins
# GET /pins.json
def index
@pins = Pin.order("created_at desc")
respond_to do |format|
format.html # index.html.erb
format.json { render json: @pins.map{|pin| pin.to_jq_upload } }
end
end
# GET /pins/1
# GET /pins/1.json
def show
@pin = Pin.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @pin }
end
end
# GET /pins/new
# GET /pins/new.json
def new
@pin = current_user.pins.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @pin }
end
end
# GET /pins/1/edit
def edit
@pin = current_user.pins.find(params[:id])
end
# POST /pins
# POST /pins.json
def create
@pin = current_user.pins.new(params[:pin])
respond_to do |format|
if @pin.save
format.html {
render :json => [@pin.to_jq_upload].to_json,
:content_type => 'text/html',
:layout => false
}
format.json { render json: [@pin.to_jq_upload].to_json, status: :created, location: @pin }
else
format.html { render action: "new" }
format.json { render json: @pin.errors, status: :unprocessable_entity }
end
end
end
# PUT /pins/1
# PUT /pins/1.json
def update
@pin = current_user.pins.find(params[:id])
respond_to do |format|
if @pin.update_attributes(params[:pin])
format.html { redirect_to @pin, notice: 'Pin was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @pin.errors, status: :unprocessable_entity }
end
end
end
# DELETE /pins/1
# DELETE /pins/1.json
def destroy
@pin = current_user.pins.find(params[:id])
@pin.destroy
respond_to do |format|
format.html { redirect_to pins_url }
format.json { head :no_content }
end
end
end
Form Partial
<%= form_for Pin.new, :url => pins_path, :html => { :multipart => true, :id => "fileupload" } do |f| %>
<!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->
<div class="row fileupload-buttonbar">
<div class="span7">
<!-- The fileinput-button span is used to style the file input field as button -->
<span class="btn btn-success fileinput-button">
<i class="icon-plus icon-white"></i>
<span>Add files...</span>
<%= f.file_field :image, :multiple => true, :name => "image[image]" %>
</span>
<button type="submit" class="btn btn-primary start">
<i class="icon-upload icon-white"></i>
<span>Start upload</span>
</button>
<button type="reset" class="btn btn-warning cancel">
<i class="icon-ban-circle icon-white"></i>
<span>Cancel upload</span>
</button>
<button type="button" class="btn btn-danger delete">
<i class="icon-trash icon-white"></i>
<span>Delete</span>
</button>
<input type="checkbox" class="toggle">
</div>
<div class="span5">
<!-- The global progress bar -->
<div class="progress progress-success progress-striped active fade">
<div class="bar" style="width:0%;"></div>
</div>
</div>
</div>
<!-- The loading indicator is shown during image processing -->
<div class="fileupload-loading"></div>
<br>
<!-- The table listing the files available for upload/download -->
<table class="table table-striped"><tbody class="files" data-toggle="modal-gallery" data-target="#modal-gallery"></tbody>
</table>
<% end %>
<div id="dropzone" class="fade well">Drop files here</div>
<script>
var fileUploadErrors = {
maxFileSize: 'File is too big',
minFileSize: 'File is too small',
acceptFileTypes: 'Filetype not allowed',
maxNumberOfFiles: 'Max number of files exceeded',
uploadedBytes: 'Uploaded bytes exceed file size',
emptyResult: 'Empty file upload result'
};
</script>
<!-- The template to display files available for upload -->
<script id="template-upload" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
<tr class="template-upload fade">
<td class="preview"><span class="fade"></span></td>
<td class="name"><span>{%=file.name%}</span></td>
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>
{% if (file.error) { %}
<td class="error" colspan="2"><span class="label label-important">{%=locale.fileupload.error%}</span> {%=locale.fileupload.errors[file.error] || file.error%}</td>
{% } else if (o.files.valid && !i) { %}
<td>
<div class="progress progress-success progress-striped active"><div class="bar" style="width:0%;"></div></div>
</td>
<td class="start">{% if (!o.options.autoUpload) { %}
<button class="btn btn-primary">
<i class="icon-upload icon-white"></i>
<span>{%=locale.fileupload.start%}</span>
</button>
{% } %}</td>
{% } else { %}
<td colspan="2"></td>
{% } %}
<td class="cancel">{% if (!i) { %}
<button class="btn btn-warning">
<i class="icon-ban-circle icon-white"></i>
<span>{%=locale.fileupload.cancel%}</span>
</button>
{% } %}</td>
</tr>
{% } %}
</script>
<!-- The template to display files available for download -->
<script id="template-download" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
<tr class="template-download fade">
{% if (file.error) { %}
<td></td>
<td class="name"><span>{%=file.name%}</span></td>
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>
<td class="error" colspan="2"><span class="label label-important">{%=locale.fileupload.error%}</span> {%=locale.fileupload.errors[file.error] || file.error%}</td>
{% } else { %}
<td class="preview">{% if (file.thumbnail_url) { %}
<a href="{%=file.url%}" title="{%=file.name%}" rel="gallery" download="{%=file.name%}"><img src="{%=file.thumbnail_url%}"></a>
{% } %}</td>
<td class="name">
<a href="{%=file.url%}" title="{%=file.name%}" rel="{%=file.thumbnail_url&&'gallery'%}" download="{%=file.name%}">{%=file.name%}</a>
</td>
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>
<td colspan="2"></td>
{% } %}
<td class="delete">
<button class="btn btn-danger" data-type="{%=file.delete_type%}" data-url="{%=file.delete_url%}">
<i class="icon-trash icon-white"></i>
<span>{%=locale.fileupload.destroy%}</span>
</button>
<input type="checkbox" name="delete" value="1">
</td>
</tr>
{% } %}
</script>
<script type="text/javascript" charset="utf-8">
$(function () {
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload();
//
// Load existing files:
$.getJSON($('#fileupload').prop('action'), function (files) {
var fu = $('#fileupload').data('fileupload'),
template;
fu._adjustMaxNumberOfFiles(-files.length);
console.log(files);
template = fu._renderDownload(files)
.appendTo($('#fileupload .files'));
// Force reflow:
fu._reflow = fu._transition && template.length &&
template[0].offsetWidth;
template.addClass('in');
$('#loading').remove();
});
});
</script>
<script type="text/javascript" charset="utf-8">
$(document).bind('dragover', function (e) {
var dropZone = $('#dropzone'),
timeout = window.dropZoneTimeout;
if (!timeout) {
dropZone.addClass('in');
} else {
clearTimeout(timeout);
}
if (e.target === dropZone[0]) {
dropZone.addClass('hover');
} else {
dropZone.removeClass('hover');
}
window.dropZoneTimeout = setTimeout(function () {
window.dropZoneTimeout = null;
dropZone.removeClass('in hover');
}, 100);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment