Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting only file name as string

i am trying to upload a file in rails

i have created a model with following code

def self.save(upload,id)
    name =  upload[:img].original_filename
    directory = "public/user_db"
    # create the file path
    path = File.join(directory, id)
    # write the file
    File.open(path, "wb") { |f| f.write(upload['img'].read) }
  end
end

my view have following field.

<div class="field">
  <input type="file" name="img" id="img" placeholder="upload your DP" />
</div>

my controller is calling save function as following :

post = DataFile.save(params,@fbuser.id)

But a am getting this errorenter image description here

like image 484
wasipeer Avatar asked Jul 09 '26 19:07

wasipeer


2 Answers

do yourself a favor and don't reinvent the wheel. In Rails there are 3 awesome gems to handle file-uploading with eatch having a great community for support and tons of shared code.

Carrierwave https://github.com/carrierwaveuploader/carrierwave

Paperclip https://github.com/thoughtbot/paperclip

Dragonfly https://github.com/markevans/dragonfly

Just follow the instructions for Installation, migrate the database, tell your models how to behave and you lost all the headache within 5 minutes :-)

regarding your problem-

name = upload[:img].original_filename this throws an expection because upload[:img] ist just containing a string. So there is no need for the .original_filename

but again - please use one of those gems (or maybe just read the code to get an idea of how to do). There are also Railscasts out there http://railscasts.com/episodes/253-carrierwave-file-uploads and http://railscasts.com/episodes/134-paperclip https://www.youtube.com/watch?v=gp_kn6afl-Y

cheers

like image 121
Tim Kretschmer Avatar answered Jul 13 '26 15:07

Tim Kretschmer


A have just the tag in view and very thing start working :) thanks for your help. the line is following

<%= f.file_field "img" %>

and in controller

post = DataFile.save(params[:fbuser],@fbuser.id.to_s)
like image 22
wasipeer Avatar answered Jul 13 '26 16:07

wasipeer