fade2black
fade2black

Reputation: 614

Where is located the temporary folder when we upload a file

I am writing Ruby-on-Rails application that stores records in a db table (number of records is not more than 200 rows). Each record is associated with an jpeg/png image or icon (max size 32x32). So my app has to upload and save the images on the server in a specific folder.

In the documentation it says "The object in the params hash is an instance of a subclass of IO. Depending on the size of the uploaded file it may in fact be a StringIO or an instance of File backed by a temporary file.".

My question: where is this temporary folder located on the server? Is it system dependent or application dependent?

Upvotes: 3

Views: 5797

Answers (1)

akatakritos
akatakritos

Reputation: 9858

The location of your tempfile is probably system dependent, likely in the /tmp folder somewhere.

But you dont really need to know.

The uploaded image is either in memory as a StringIO object, or saved to a temporary file on the host server. This is an optimization provided by rails. If the image is small enough, Rails will pass you a StringIO object, which is basically the entire image loaded in memory. If the image is larger, it will pass you an instance that represents a temporary file on disk.

You want to just save it to a known folder, say uploads. You do not need to care if the image is stored in memory or stored on disk.

Both StringIO objects and temp file backed objects respond to the :read method. All you have to do is call read to get the data and then write it out to the location you want.

image_as_io = params[:image]
filename = ... # determine a filename for the image

File.open(Rails.root.join('public', 'uploads', filename), 'wb') do |file|
  file.write(image_as_io.read)
end

Upvotes: 3

Related Questions