简体   繁体   中英

Unable to send image from frontend to cloudinary or the backend in general

I am trying to send an image from the frontend to cloudinary to be used as profile picture in my app using the code below:

import { StyledInput, StyledLabel} from '../FormInputs/styles'
import { useState } from 'react'
import { StyledButton } from '../Button/styles'
import axios from 'axios'

export function FileUploader() {
  const [file, setFile] = useState(null)
  const [image, setImage] = useState(null)
  const [showImage, setShowImage] = useState()

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

  function readFile(file) {
    const reader = new FileReader()

    reader.readAsDataURL(file)

    reader.onload = e => setImage(e.target.result)
    reader.onerror = e => console.log(reader.error)

  }

  async function handleSubmit(e) {
    e.preventDefault()
    const token = localStorage.getItem('token')

    const data = new FormData()
    if(file) {
      data.append('file', file[0], file[0].name)
    }

  const response = await axios({
    method: 'PUT',
    base: 'http://localhost:8000',
    url: '/clients/clientprofile',
    data,
    headers: {
      'Content-Type': 'multipart/form-data',
      'Authorization': `Bearer ${token}`
    }
  })

  console.log(response)
  // setShowImage(response.image)
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <StyledLabel htmlFor="file">Elegir foto de perfil</StyledLabel>
        <StyledInput
          type="file"
          accept="image/*"
          name="file"
          id="file"
          onChange={handleChange}
        />
        <StyledButton type="submit">Enviar Foto</StyledButton>
      </form>
      {image && <img src={image} alt="Profile Picture Preview" />}
    </div>
  )
}

When I select the image it works fine, however, when I click the "Upload Image" button, it errors out with the below error:

1

I am defining file by using the setFile() , however, when I console.log(file) it returns null

Since the console.log() is async, it was logging null because it was executing before the state had time to change, and the issue with the undefined was due to an error of the config in the backend.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM