dimanche 24 avril 2016

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

Aucun commentaire:

Enregistrer un commentaire