简体   繁体   English

如何在Rails中将文件上传到服务器?

[英]How to upload files to the server in rails?

i am willing to upload the file to the server without using any gem. 我愿意不使用任何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: 我在创建acrion中使用了上述功能,如下所示:

@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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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