上一篇帖子https://ruby-china.org/topics/28411 里面,大家推荐的 simditor 太捧了,于是二话不说正在折腾更换 pagedown,使用的是 @stone 推荐的https://github.com/wentaoliu/simditor-rails
目前有两个问题:
加一个 hidden
<%= f.text_field :body, :type=> 'hidden'%>
我的 rails 代码是这样的
<div class="sky-form">
<%= simple_form_for(@post) do |f| %>
<fieldset>
<section>
<label class="label"><strong><%= t('posts.title') %></strong></label>
<label class="input"><%= f.text_field :title,placeholder: t('posts.title')%></label>
</section>
<label class="label"><strong>Tag</strong></label>
<label class="input"><%= f.text_field :tag_list, placeholder: t('videos.tagshint') %></label>
<%= f.text_field :body%>
<%= f.submit t('posts.post'), :class => 'btn btn-success' %>
</fieldset>
</div>
<% end %>
<script type="text/javascript">
var editor = new Simditor({
textarea: $('#post_body'),
placeholder: '这里输入文字...',
pasteImage: true,
upload: {
url: '/photos',
// params: null,
fileKey: 'upload_file',
connectionCount: 3,
leaveConfirm: 'Uploading is in progress, are you sure to leave this page?'
}
});
</script>
方法:
##routes.rb
- resources :photos, only: [:image]
+ post 'photos' => 'photos#image'
def image
@photo = Photo.new(image: params[:upload_file])
@photo.user_id = current_user.id
if @photo.save
render json: { ok: true, url: @photo.image.url }
else
render json: { ok: false }
end
end
` 使用以下种直接写入的上传方式没有问题,参考的是http://my.oschina.net/huangwenwei/blog/408998?fromerr=xLh23Gdz的代码,
def image
file = params[:upload_file]
file_list = []
success = true
msg = '上传成功'
file_real_path = ''
if !file.content_type.match(/^image\/(gif|png||jpg||jpeg|){1}$/)
success = false
msg = "#{file.original_filename}:只支持上传JPG,JPEG,PNG格式图片"
elsif file.size > 2*1024*1024
success = false
msg = "#{file.original_filename}:图片太大,请上传小于2M的图片"
end
if success
file_real_path = save_file(file)
file_list << file_real_path
end
logger.info file_real_path
render json: {:success=>success, :msg=>msg,:file_path=>"/#{file_real_path}" }
end
private
def save_file(file)
extname = file.content_type.match(/^image\/(gif|png|jpg|jpeg){1}$/).to_a[1]
filename = File.basename(file.original_filename,'.*')
uri = File.join('photo','images',"#{DateTime.now.strftime('%Y/%m%d/%H%M%S')}_#{SecureRandom.hex(4)}_#{current_user.id}.#{extname}")
save_path = Rails.root.join('public',uri)
file_dir = File.dirname(save_path)
FileUtils.mkdir_p(file_dir) unless Dir.exists?(file_dir)
File.open save_path, 'wb' do |f|
f.write(file.read)
end
return uri
end
但是我想把上传写入数据库,使用代码:
def image
@photo = Photo.new(image: params[:upload_file])
if @photo.image.blank?
render json: { ok: false }, status: 400 and return
end
@photo.user_id = current_user.id
if @photo.save
render json: { ok: true, url: @photo.image.url }
else
render json: { ok: false }
end
end
photo.image 一直是 nil 的?上传一直不成功? `