簡體   English   中英

通常無法將圖像從前端發送到雲端或后端

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

我正在嘗試使用以下代碼將圖像從前端發送到 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>
  )
}

當我 select 圖像工作正常時,但是,當我單擊“上傳圖像”按鈕時,它會出現以下錯誤:

1

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

由於console.log()是異步的,它正在記錄 null 因為它在state有時間更改之前執行,並且未定義的問題是由於后端配置錯誤造成的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM