Paperclip:保存Base64编码的文件,不带扩展名保存
Paperclip: Saving Base64 encoded file, saved without extension
我试图在 rails 上使用回形针保存 Base64 编码的字符串,但生成的文件没有扩展名
编码后的字符串如下:
{"model"=>{"photo"=>"data:image/jpeg;base64,/9j..}
曲别针配置
has_attached_file :photo,
:styles => { medium: "380x380>", small: "200x200>", thumb: "100x100>" },
:path => ":rails_root/model/:style/:id.:extension",
:url => "/object_image/model/:style/:id.:extension",
:default_url => "/images/default-avatar.png"
validates_attachment_content_type :photo,
:content_type => ["image/jpg", "image/jpeg",
"image/png", "image/gif"]
生成的文件是:1.
感谢任何帮助。
谢谢
尝试使用图像的内容类型来设置扩展名
tempfile = self.image.queued_for_write[:original]
unless tempfile.nil?
extension = File.extname(tempfile.original_filename)
if !extension || extension == ''
mime = tempfile.content_type
ext = Rack::Mime::MIME_TYPES.invert[mime]
self.image.instance_write :file_name, "#{tempfile.original_filename}#{ext}"
end
end
特别感谢 Whosebug。
我遇到了同样的问题,但我真的不在乎文件是否有扩展名,因为我正在将它上传到 s3。为了做一些其他的事情,我需要获得文件扩展名。这是我在上传后从 base64 编码文件中获取文件扩展名的解决方案。
在model.rb
file_path = attachment.queued_for_write[:original].path
# tmp/filename_without_extension
ext = '.' + attachment.queued_for_write[:original].content_type.downcase.split('/').last
# .content_type returns something like "image/png"```
我试图在 rails 上使用回形针保存 Base64 编码的字符串,但生成的文件没有扩展名
编码后的字符串如下:
{"model"=>{"photo"=>"data:image/jpeg;base64,/9j..}
曲别针配置
has_attached_file :photo,
:styles => { medium: "380x380>", small: "200x200>", thumb: "100x100>" },
:path => ":rails_root/model/:style/:id.:extension",
:url => "/object_image/model/:style/:id.:extension",
:default_url => "/images/default-avatar.png"
validates_attachment_content_type :photo,
:content_type => ["image/jpg", "image/jpeg",
"image/png", "image/gif"]
生成的文件是:1.
感谢任何帮助。 谢谢
尝试使用图像的内容类型来设置扩展名
tempfile = self.image.queued_for_write[:original]
unless tempfile.nil?
extension = File.extname(tempfile.original_filename)
if !extension || extension == ''
mime = tempfile.content_type
ext = Rack::Mime::MIME_TYPES.invert[mime]
self.image.instance_write :file_name, "#{tempfile.original_filename}#{ext}"
end
end
特别感谢 Whosebug。
我遇到了同样的问题,但我真的不在乎文件是否有扩展名,因为我正在将它上传到 s3。为了做一些其他的事情,我需要获得文件扩展名。这是我在上传后从 base64 编码文件中获取文件扩展名的解决方案。
在model.rb
file_path = attachment.queued_for_write[:original].path
# tmp/filename_without_extension
ext = '.' + attachment.queued_for_write[:original].content_type.downcase.split('/').last
# .content_type returns something like "image/png"```