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 error
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With