简体   繁体   English

Ruby on Rails文件上传和下载

[英]Ruby on rails File Upload and download

Here I want to fulfil the function which is to upload file and then download in ruby on rails. 在这里,我要实现的功能是上传文件,然后在Rails中以ruby下载。

First I add function in Application Controller 首先,我在Application Controller中添加功能

def uploadFile(file)
if !file.original_filename.empty
  @filename = getFileName(file.original_filename)
  File.open("#{RAILS_ROOT}/public/files/#{@filename}", "wb") do |f|
    f.write(file.read)
  end
  return @filename
end
end

def getFileName(filename)
if !filename.nil
  return filename
end
end

def save(file, description)
@filename=getFileName(file.original_filename)
@filesize=getFileName(file.length)
@uploadfile = Uploadfile.new
@uploadfile.filename=@filename
@uploadfile.filesize=@filesize/1024
@uploadfile.description=description
@uploadfile.save
end

Second, I add upload in my controller which is for file upload. 其次,我在控制器中添加用于文件上传的上传。

def upload
@uploadfile = Uploadfile.new
unless request.get
  i=params[:file].size
  for num in(0..i-1)
  if filename=uploadFile(params[:file][num])
    savefiles(params[:file][num],params[:uploadfile][num])
  end
end
end
end

Finally, I add html in my new.html.erb which is the page I am gonna to upload file and submit. 最后,我在new.html.erb中添加html,这是我要上传文件并提交的页面。

  <%=form_tag ({:action=>"upload"}), :multipart=>true %>
  <divid="MyFile">
  <inputid="file"name="file[]"size="30"type="file"/></br>
  <inputtype="text"id="uploadfile_description"name="uploadfile[]"></br>
</div>
<inputtype="button"value="add"onclick="addText()"/>
<inputstyle="cursor:pointer"type="submit"value="upload"/>
<%=form_tag%>

Eventually, I still got mistakes on this. 最终,我仍然在此方面犯错误。

No route matches {:action=>"upload", :controller=>"cplectures"} 没有路线匹配{:action =>“ upload”,:controller =>“ cplectures”}

How am I going to fix it without paperclip or other gems, and after that how to download this file from the front side with a download button. 我该如何在不使用回形针或其他宝石的情况下进行修复,以及如何使用下载按钮从正面下载此文件。 Thanks guys 多谢你们

It seems your form us sending GET where it should be a POST or vice-versa. 看来您的表格是我们发送GET地方,应该是POST ,反之亦然。 First, check your routes by running: 首先,通过运行以下命令检查路线:

rake -T

and find your controller, action combination there. 并在那里找到您的控制器和动作组合。 Check the http verb expected, and send it with your form like this: 检查所需的http动词,并使用以下形式发送:

<%= form_tag "", method: :get %>

assuming your post is happening to the same route you're in. 假设您的帖子与您所走的路线相同。

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

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