简体   繁体   中英

How to upload files to the server in rails?

i am willing to upload the file to the server without using any gem. Following is what i have tried:

the following is the function that i have created in modal:

def self.file_upload(uploaded_file)
    puts uploaded_file
    file = Tempfile.new(uploaded_file, 'http://52.41.99.60/GEMWebservices/Image')

    returning File.open(file.path, 'w') do |f|
      f.write file.read
      f.close
    end
  end

I have used the above function in create acrion as follows:

@file_upload = User.file_upload(params[:uploaded_file])

But i get the following error:

unexpected prefix: #<ActionDispatch::Http::UploadedFile:0x007fa0909fbe00 @tempfile=#<Tempfile:/var/folders/tt/d903z3v94sbgr8yymqxn_m0m0000gn/T/RackMultipart20160829-27648-gzgzt8.jpeg>, @original_filename="kaka.jpeg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"uploaded_file\"; filename=\"kaka.jpeg\"\r\nContent-Type: image/jpeg\r\n">

Can any one help me out? Thank you in advance.

Try this code snippet :

def file_upload(file)
  file_path = '/GEMWebservices/Image/'+file.original_filename
  File.open(Rails.root.join('public', 'GEMWebservices','Image',file.original_filename), 'wb') do |f|
    f.write(file.read)
  end
  file_path
end

In action:

@file_upload = file_upload(params[:uploaded_file])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM