文件上传重复保存文件指针移位

遇到一种情况,上传一个文件需要遍历保存多遍的时候,只有第一次文件保存生效。发现是文件保存的时候文件指针指到了尾部,导致文件再保存的时候读不到内容。

解决办法:
一:将文件保存再没次open重新读写。

path = "#{Rails.root}"+payment_bill.file_name
content_type =  MIME::Type.simplified(%x{file --mime -b #{path} }.chomp)
_temp_f = File.open(path)
_payment_info.ebuychem_attachments.create(:attachment_file => _temp_f,:file_name => new_payment.payment_bill_file_name,:content_type =>content_type ) if params[:payment_info][:payment_bill]
_temp_f.close

二:每次将文件指针重新回到头指针位置

params[:payment_info][:payment_bill].rewind

payment_info.ebuychem_attachments.create(:attachment_file => params[:payment_info][:payment_bill])

总结:ruby提供了 rewind  seek等指针移动方法。

猜你喜欢

转载自schooltop.iteye.com/blog/2323330