我有一个创建产品页面和一个添加照片页面。用户创建产品后,他们会被重定向到允许他们添加照片的页面。我正在使用Jquery 文件上传,它显示您选择的图片的预览,然后在单击开始时将它们添加到服务器。但是,我收到此错误。
jQuery文件上传错误
DWadeCrop.jpg 97.74 KB 错误语法错误:JSON.parse:意外字符
控制台消息
Started POST "/photos" for 127.0.0.1 at 2013-07-10 21:03:03 -0400
Processing by PhotosController#create as JSON
Parameters: {"utf8"=>"✓", "authenticity_token"=>"tc6sbe9n/PPKlZlUpQYWqxR3C6QJEMnQJSKr8+prczw=", "product_id"=>"129", "photo"=>{"upload"=>#<ActionDispatch::Http::UploadedFile:0xa5f0780 @original_filename="DWadeCrop.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"photo[upload]\"; filename=\"DWadeCrop.jpg\"\r\nContent-Type: image/jpeg\r\n", @tempfile=#<File:/tmp/RackMultipart20130710-3967-h6rcoo>>}}
Product Load (0.1ms) SELECT "products".* FROM "products" WHERE "products"."id" = ? LIMIT 1 [["id", "129"]]
Redirected to http://localhost:3000/
Completed 302 Found in 5ms (ActiveRecord: 0.1ms)
Started GET "/" for 127.0.0.1 at 2013-07-10 21:03:03 -0400
Processing by StaticPagesController#home as JSON
Rendered static_pages/home.html.haml within layouts/application (1.4ms)
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."auth_token" = 'eQOQkRRSnzfA51iiDQ-90w' LIMIT 1
Completed 200 OK in 85ms (Views: 84.6ms | ActiveRecord: 0.3ms)
上传照片查看位置 localhost:3000/products/123/pics
Upload file
= form_for @photo, :html => { :multipart => true, :id => "fileupload" } do |f|
= f.file_field :upload
= hidden_field_tag 'product_id', @photo.product_id
图片的方法
def pics
@product = Product.find(params[:product_id])
@photo = Photo.new
@photo.product_id = @product.id
end
为照片创建方法
def create
@product = Product.find(params[:product_id])
@photo = Photo.new
if @photo.valid?
@photo.product_id = @product.id
@photo.save!
respond_to do |format|
format.html { redirect_to product_path(@product) }
format.json { render json: @photo }
end
else
redirect_to root_url, :notice => "Somehting went wrong!"
end
end
照片模型
class Photo < ActiveRecord::Base
attr_accessible :image
has_attached_file :image
include Rails.application.routes.url_helpers
belongs_to :product
validates_attachment :image, presence: true,
content_type: { content_type: ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'] },
size: { less_than: 5.megabytes }
has_attached_file :image, styles: { medium: "320x240>", :thumb => "100x100>"}
def to_jq_image
{
"name" => read_attribute(:upload_file_name),
"size" => read_attribute(:upload_file_size),
"url" => image.url(:original),
"delete_type" => "DELETE"
}
end
end