【问题标题】:How to upload files to the server in rails?如何在rails中将文件上传到服务器?
【发布时间】:2017-01-09 08:44:30
【问题描述】:

我愿意在不使用任何 gem 的情况下将文件上传到服务器。以下是我尝试过的:

以下是我在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

我在create acrion中使用了上面的函数如下:

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

但我收到以下错误:

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">

谁能帮帮我?提前谢谢你。

【问题讨论】:

    标签: ruby-on-rails image uploading


    【解决方案1】:

    试试这个代码 sn-p :

    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
    

    在行动:

    @file_upload = file_upload(params[:uploaded_file])
    

    【讨论】:

      猜你喜欢
      • 2011-02-12
      • 2017-04-25
      • 2019-06-24
      • 2011-09-25
      • 2020-03-17
      • 2014-10-17
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      相关资源
      最近更新 更多