简体   繁体   中英

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.

First I add function in 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.

  <%=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"}

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. 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:

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

assuming your post is happening to the same route you're in.

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