【问题标题】:Unable to send image from frontend to cloudinary or the backend in general通常无法将图像从前端发送到云端或后端
【发布时间】:2021-07-08 21:05:34
【问题描述】:

我正在尝试将图像从前端发送到 cloudinary,以用作我的应用中的个人资料图片。请在下面找到执行此操作的代码:

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>
  )
}

当我选择图片时,它工作正常,但是,当我点击“上传图片”按钮时,它会出现以下错误:

我正在使用setFile() 定义文件,但是,当我console.log(file) 它返回null

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript node.js reactjs image cloudinary


    【解决方案1】:

    由于console.log() 是异步的,它正在记录null,因为它在state 有时间更改之前执行,而未定义的问题是由于后端配置错误造成的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      • 2018-02-02
      • 1970-01-01
      相关资源
      最近更新 更多