user1573607
user1573607

Reputation: 522

Rails - Uploading zip file with paperclip and unziping

I'm trying to upload a zip file using rails and paperclip gem, and so far it works fine. But after download has finished, I want to unzip this file and do some things with the files inside.

The problem appears when I try to unzip the file, because it isn't in it's own path, probably it's being copied but has no finished. (And I'm in localhost, worse in online mode).

So, I need some kind of event/trigger to know when the file has finished uploading to start unziping. And meanwhile, show some kind of interface. The code of the controler goes below:

# POST /components
# POST /components.json
def create
  @component = Component.new(params[:component])

  file = @component.folder

  Zip::ZipFile.open(file.path) do |zipfile|   # <-- The error comes here
    zipfile.each do |file|
      # do something with file
    end
  end


  respond_to do |format|
    if @component.save
      format.html { redirect_to @component, notice: 'Component was successfully created.' }
      format.json { render json: @component, status: :created, location: @component }
    else
      format.html { render action: "new" }
      format.json { render json: @component.errors, status: :unprocessable_entity }
    end
  end
end

Upvotes: 2

Views: 2676

Answers (2)

Avadh B S Dwivedi
Avadh B S Dwivedi

Reputation: 145

Here is an unzip function that might be helpful in your case, see if this works for you.

def create_photos_from_zip logger.debug "create_photos_from_zip -->" zip = params[:zip] logger.debug "unzipping file #{zip.path} class #{zip.class}"

dir = File.join(RAILS_ROOT,"public","events","temp",current_user.name)
FileUtils.mkdir_p(dir)
Zip::ZipFile.open(zip.path).each do |entry|
  # entry is a Zip::Entry
  filename = File.join(dir,entry.name)
  logger.debug "will extract file to #{filename} to"
  entry.extract(filename)
  p = File.new(filename)
  photo = Photo.create(:photo=>p)
  photo.title = "nova imagem"
  @event.photos << photo 
  p.close
  FileUtils.remove_file(filename)
end
#delete zip file
logger.debug "closing/deleting zip file #{zip.path}"
zip.close
FileUtils.remove_file(zip.path)
logger.debug "saving the event to database"
logger.debug "create_photos_from_zip <--"

end

Upvotes: 1

Daniel Jacobs
Daniel Jacobs

Reputation: 91

Not sure if this would help as I am struggling with paperclip myself but here goes.

I would expect that after the save method has been called and completed that the file would be saved. I would suggest that you call your additional actions on the file after the save method.

Hope it helps.

Upvotes: 0

Related Questions