Giter Club home page Giter Club logo

sinatra-react-file-upload-demo-frontend's Introduction

Sinatra/React Image Upload Demo

(Backend repo is here: https://github.com/marcmajcher/sinatra-react-file-upload-demo-backend)

Set up the Sinatra template for the backend

  1. clone https://github.com/learn-co-curriculum/phase-3-sinatra-react-project.git image-upload-backend
  2. cd image-upload-backend
  3. rm -rf .canvas .git .github
  4. bundle install
  5. git init; git add . ; git commit -m init
  6. rake server

Set up a React app for the frontend

  1. npx create-react-app image-upload-frontend
  2. cd image-upload-frontend
  3. npm start
  4. (optional) delete all the junk from the default react app: webvitals, logo, boilerplate App, etc

Add the upload form on the frontend

<h1>Upload File</h1>
<form onSubmit={uploadImage}>
  <label htmlFor="file">File:</label>
  <input type="file" name="image" onChange={handleImageChange} />
  <button type="submit">Upload</button>
</form>

Set up your handlers

const [imageUrl, setImageUrl] = useState();
const [file, setFile] = useState();

function handleImageChange(e) {
  setFile(e.target.files[0])
  console.log(e.target.files[0])
}

function uploadImage(e) {
  e.preventDefault();
  const formData = new FormData();
  formData.append('image', file);

  fetch('http://localhost:9292/upload', {
    method: 'POST',
    body:formData,
  })
    .then((res) => res.json())
    .then(json => setImageUrl(`http://localhost:9292/${json.url}`));
}

Add a bit to display the image once uploaded

{ imageUrl ? <img src={imageUrl} alt={imageUrl} /> : '' }

On the backend:

  • create folder in app: public/images
  • in ApplicationCcntroller, set the public dir:
set :public_folder, 'app/public'
  • and image directory:
set :image_dir, File.join(settings.public_folder, 'images')

In your controller, add the upload route

post '/upload' do
  if params[:image]
    filename = params[:image][:filename]
    tempfile = params[:image][:tempfile]
    FileUtils.copy(tempfile, File.join(settings.image_dir, filename))
    {status: "ok", url: "/images/#{filename}"}.to_json
  else
    {status: "error", message: "no file"}
  end
end

Now when you submit a file through the form, the backend will grab the filename and the temporary file, copy the temp file to the images dir, and send back a url to access it!

sinatra-react-file-upload-demo-frontend's People

Contributors

marcmajcher avatar

Watchers

 avatar James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.