Z
Z
zachfischer2018-07-16 13:19:45
Ruby on Rails
zachfischer, 2018-07-16 13:19:45

How can I implement a controller for uploading and downloading files?

I have applications where the backend is Rails 5, and the frontend is Angular 5. I can't figure out how to write a controller and routing so that in the future you can download and upload files using the Angular service. The normal controller I'm using doesn't work:

class FilesController < ApplicationController
  before_action :set_file, only: [:show, :update, :destroy]

  def index
    @files = File.all

    render json: @files
  end

def show
  render json: @file
end

def create
  @file = File.new(files_params)

  if @file.save
    render json: @file, status: :created, location: @file
  else
    render json: @file.errors, status: :unprocessable_entity
  end
end

def update
  if @file.update(files_params)
    render json: @file
  else
    render json: @file.errors, status: :unprocessable_entity
  end  
end

def destroy
  @file.destroy
end

private
  def set_file
    @file = File.find(params[:id])
  end

  def files_params

    params.require(:file).permit!
  end
end

For example, for now I just want to see what is loaded there by clicking on the link localhost: 3000/files, it gives the following error:
Completed 500 Internal Server Error in 1595ms

Encoding::UndefinedConversionError ("\xFF" from ASCII-8BIT to UTF-8):

app/controllers/spr_files_controller.rb:7:in `index'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Mirilaczvili, 2018-07-16
@2ord

File is a built-in class in Ruby for working with files on the local file system.
There in FilesController the complete nonsense is written.
What means:

@file = File.find(params[:id])
@files = File.all
@file = File.new(files_params)
@file.update(files_params)
@file.destroy

Google: screencast rails upload files

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question