How to read and write files?


#1

Dear all,

I have uploaded gif images and stored in folder called banner list. I
have successfully read and written the uploaded gif files even animated
gif files. But when i read the same gif file from the the bannerlist
folder and write in banner folder, i was not able to do so. Please
suggest on how to read gif images from a folder and write in another
folder.

I have used code :

if File.exists? RAILS_ROOT + “/public/images/bannerlist/#{params[:id]}”

a = File.read(“public/images/bannerlist/martin2.gif”)

File.open(“public/images/banner/” + “banner.gif” , “wb”) do |f|

  f.write(a)

end
end

For Uploading of images i have used following code and it works fine, so
please suggest on the above issue of reading and writing of animated gif
files from one folder to another.

image = params[:image][:blob]

image1=params[:image][:blob].original_filename

File.open(RAILS_ROOT + “/public/images/bannerlist/” + image1, “wb”) do
|f|

f.write(params[:image][:blob].read)

end

please suggest a way for reading and writing of animated gif files from
one folder to another.

Thanks in advance

Regards,
Jose


#2

dare ruby wrote:

I have used code :

if File.exists? RAILS_ROOT + “/public/images/bannerlist/#{params[:id]}”

Firstly, start using Pathname. I always put this in environment.rb:

require ‘pathname’
RailsRoot = Pathname.new(RAILS_ROOT).expand_path

That allows this:

if (RailsRoot + ‘public/images/bannerlist’ + params[:id]).exist?

a = File.read(“public/images/bannerlist/martin2.gif”)

That .read() call neglects the RAILS_ROOT. Never guess what the current
folder
is; always use complete paths.

Next, you are essentially reading a gif into memory and barfing it out
into a
file. This is slow, fragile, and high-risk. Consider using FileUtils to
symlink
the banner.gif to the rotating banner in the banner list.


Phlip


#3

Why are you reading one file and then writing it to another?

Why don’t you just copy it? http://is.gd/gNve

And if file operations doesn’t work, open up console and try it there.
You will see if it was successful, because irb will show true/false.
If it’s false, then check if your directories have rights to be
writed.

On 22. Jan, 05:46 h., dare ruby removed_email_address@domain.invalid


#4

file. This is slow, fragile, and high-risk. Consider using FileUtils to
symlink
the banner.gif to the rotating banner in the banner list.

Dear Philip thanks for your immediate response, it works fine with
FileUtils copy method. Thanks for your suggestions.

Regards,
Jose Martin