我花了很多时间使用ng-file-upload和rails paperclip并卡住了((。在标准视图中使用new.html.erb paperclip工作得很完美。但是使用ng-file-upload浏览器会返回错误。
Internal Server Error
bad content body
或者如果我在控制器中更改上传:
afisha: {file: file} => to file: {file: file}
路由错误:
Routing Error
No route matches [POST] "/public"
这是我的控制器:
$scope.upload = function (file) {
console.log(file);
Upload.upload({
url: 'http://localhost:3000/public',
method: 'POST',
afisha: {file: file}
}).then(function (resp) {
console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
}, function (resp) {
console.log('Error status: ' + resp.status);
}, function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
});
};
查看:
<button class="btn" ngf-select="upload($file)">Upload on file select</button>
Rails控制器:
class EventsController < ApplicationController
respond_to :json
before_filter :authenticate_user!
def index
respond_with Event.all
end
def show
respond_with Event.find(params[:id])
end
def create
@event = Event.create(event_params)
@guests = guests_params[:guests].map { |guest|
Guest.create(name: guest[:name], surname: guest[:surname], event: @event)
}
respond_with @event
end
def destroy
@event = Event.find(params[:id])
@event.destroy
end
def authenticate_user!
if user_signed_in?
super
else
redirect_to login_path
end
end
private
def event_params
params.require(:event).permit(:name, :description, :date, :afisha)
end
def guests_params
params.permit(guests: [:name, :surname])
end
end
模型:
class Event < ActiveRecord::Base
has_attached_file :afisha, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
validates_attachment_content_type :afisha, content_type: /\Aimage\/.*\z/
has_many :guests
def as_json(options={})
super(options.merge(include: :guests))
.merge(:afisha => afisha.url)
end
end