Cloudinary image upload

Home   »   Cloudinary image upload

import React, { useState } from 'react';
import { v4 as uuidv4 } from 'uuid';
import axios from 'axios';
import './App.css';

function App() {
  const baseURL = "https://api.cloudinary.com/v1_1//image/upload";
  const [selectedFiles, setSelectedFiles] = useState([]);
  const [imageUrls, setImageUrls] = useState([]);

  //Add the selected files to state
  const changeHandler = (event) => {
    let files = []
    if (event.target.files.length > 0) {

      [...event.target.files].forEach(file => {
        files.push({
          id: uuidv4(),
          item: file
        })
      });
    }
    setSelectedFiles(files);
    console.info(files)
  };


  const uploadFiles = () => {
    selectedFiles.forEach((file) => {
      let formData = new FormData();
      formData.append("file", file.item);
      formData.append("upload_preset", "");

      axios.post(baseURL, formData)
        .then((data) => {
          if (data.request.response !== '') {
            let resp = JSON.parse(data.request.response)
            return {
              id: uuidv4(),
              url: resp.secure_url
            }
          }
        })
        // Details on using previous state: https://reactjs.org/docs/hooks-reference.html#functional-updates
        .then((url) => setImageUrls(prevURLS => [...prevURLS, url]))
        .catch(err => console.error(err));
    })
  }

  return (
    

Uploaded File URLs

    { imageUrls.length > 0 ? imageUrls.map((img) => { return
  • {img.url}
  • }) : <> }
); } export default App;

Leave a Reply

Your email address will not be published.