React uploading images

How can I upload images to my array, I was using axios and JSONPlaceholder but what if I have my own array in a file named data.js and I want to upload the images in there, what would I write instead of axios.post() ?

import React, { Component } from 'react';
import axios from 'axios';
import './App.css';

class App extends Component {
  state = {
    selectedFile: null
  }

  fileSelectedHandler = event => {
    this.setState({ selectedFile: event.target.files[0] });
  }

  fileUploadHandler = () => {
    const fd = new FormData();
    fd.append("image", this.state.selectedFile, this.state.selectedFile.name);
    axios.post("https://jsonplaceholder.typicode.com/photos", fd, {
      onUploadProgress: progressEvent => {
        console.log("upload progress " + Math.round((progressEvent.loaded / progressEvent.total)*100) + "%");
      }
    })
    .then(res => {
      console.log(res);
    });
  }

  render() {
    return (
      <div className="App">
        <input type = "file" onChange = {this.fileSelectedHandler} />
        <button onClick = {this.fileUploadHandler}>upload</button>
      </div>
    );
  }
}

export default App;

below was my solution for a recent project. (using typescript and react.) this is for a drag and drop type. event.dataTransfer.files[0] will get the actual file data I believe. you would also need to make sure your headers are set to Content-Type : multipart/form-data

I don’t really understand what you are wanting to do. if you would like to upload an image to your own fileserver, you can create a backend with node.js, and multer. This makes it easy to store your images.

image

for the event:

image

I don’t currently have a backend I just want to store in the memory so I don’t know what to write instead of:

axios.post("https://jsonplaceholder.typicode.com/photos", fd, {
      onUploadProgress: progressEvent => {
        console.log("upload progress " + Math.round((progressEvent.loaded / progressEvent.total)*100) + "%");
      }
    })
    .then(res => {
      console.log(res);
    });

instead of that part, I want to upload the image to my array of objects.

1 Like

@njanne19 you knnow React right? can you help me with the fileUploadHandler method? please, how can I upload the images to my own array of objects, what I mean by this is that I have a file named data.js where I have my custom array of objects.