我想建立一个图片上传购买可以通过网络或ios应用程序,我得到一个例子https://github.com/defish16/ios-to-rails-images,我使用Rails 4
型号:
class Test < ActiveRecord::Base
attr_accessor :avatar_data
has_attached_file :avatar, :styles => { medium: ["300x300>", :png], thumb: ["100x100>", :png]}
belongs_to :project
before_save :decode_avatar_data
def decode_avatar_data
# If avatar_data is present, it means that we were sent an image over
# JSON and it needs to be decoded. After decoding, the image is processed
# normally via Paperclip.
if self.avatar_data.present?
data = StringIO.new(Base64.decode64(self.avatar_data))
data.class.class_eval {attr_accessor :original_filename, :content_type}
data.original_filename = self.id.to_s + ".png"
data.content_type = "image/png"
self.avatar = data
end
end
end
class Project < ActiveRecord::Base
has_many :avatars, class_name: 'Test', dependent: :destroy
accepts_nested_attributes_for :avatars
end
控制器
class ProjectsController < ApplicationController
def create
@project = Project.new(project_params)
respond_to do |format|
if @project.save
format.html { redirect_to @project, notice: 'Project was successfully created.' }
format.json { render action: 'show', status: :created, location: @project }
else
format.html { render action: 'new' }
format.json { render json: @project.errors, status: :unprocessable_entity }
end
end
end
def project_params
params.require(:project).permit(:name, :description, avatars_attributes: [:avatar])
end
class TestsController < ApplicationController
def create
@test = Test.new(test_params)
respond_to do |format|
if @test.save
format.html { redirect_to @test, notice: 'Test was successfully created.' }
format.json { render action: 'show', status: :created, location: @test }
else
format.html { render action: 'new' }
format.json { render json: @test.errors, status: :unprocessable_entity }
end
end
end
def test_params
params.require(:test).permit(:project, :avatar_data, :avatar)
end
我可以通过网络正常上传,但是当我尝试通过ios app上传时,我无法获取图片
这是我的日志的一部分
当我使用ios应用程序时 参数:{“avatars_attributes”=&gt; [{“avatar_data”=&gt;“/ 9j / 4AAQSkZJRgABAQAAAQABAAD / 4QBYR .......
但在网络上 参数:{“project”=&gt; {“name”=&gt;“test3”,“description”=&gt;“teset3”,“avatars_attributes”=&gt; {“0”=&gt; {“avatar”=&gt; #
这是一个问题吗?应用程序avatars_attributes中的Cuz没有出现在“项目”中,如何修复它?在应用程序或服务器中 如果没有,哪里会出错?
答案 0 :(得分:0)
您打算在模型中解码base64图像数据网址,但是您的视图中似乎没有base64数据网址,我有一个示例来说明如何将图像文件转换为数据网址(使用html5文件api,不工作&lt; IE10):