create a http server and upload a file and return a json response in ruby

Tags: HTTP, Ruby, File Upload, JSON

require 'sinatra' require 'json'

post '/upload' do unless params[:file] && (tmpfile = params[:file][:tempfile]) && (name = params[:file][:filename]) return { error: 'Please select a file to upload' }.to_json end

save the uploaded file to a desired directory

target_dir = './uploads' Dir.mkdir(target_dir) unless Dir.exist?(target_dir) target_path = File.join(target_dir, name) File.open(target_path, 'wb') { |f| f.write(tmpfile.read) }

return JSON response with a success message and the file details

{ success: true, message: "File '#{name}' has been uploaded successfully.", file: { name: name, size: File.size(target_path), url: "/uploads/#{name}" } }.to_json end

main.rb

This Ruby code uses Sinatra to create an HTTP server that listens for `POST` requests on the `/upload` endpoint. The code expects a file to be sent as a parameter with the key `file`.

If the file is not present in the request, the server returns a JSON response with an error message. If the file is present, the code saves the file to a desired directory and generates a JSON response with a success message and the file details.

Note: This code is only for demonstration purposes and is not production-ready. It lacks proper error handling, security measures, and other important features.
595 chars
7 lines

related categories

gistlibby LogSnag