如何从用户定义的输入中上传图像?

How do I upload image in react from user defined input?

我希望用户能够上传任何图片。

下面的代码给了我 URL 但在图像的 src 中使用 URL 不起作用。

还有另一种方法,您可以将文件作为对象发送到后端。那也不管用。因为我有一个用户对象和其他键值对,如“名称”、“日期”等,所以将其他整个对象添加到键中会使事情变得太复杂。

--

import React, { useState} from "react";
import { Link } from "react-router-dom";
import Axios from 'axios';

export default function PostJournalEntry(){
  /* Hooks */
  const [selectedFile, setSelectedFile] = useState();
  const [file, setFile] = useState();
  const [name, setName] = useState();
  const [title, setTitle] = useState();
  const [journalEntry, setJournalEntry] = useState();
  const [date, setDate] = useState();
  /* End of Hooks */
  
   /* Click Handlers */
  const handleName = (e)=>{
      setName("Anonynamus")
  }
  const handleTitle = (e)=>{
    setTitle(e.target.value)
  }
  const handleJournalEntry = (e)=>{
    setJournalEntry(e.target.value)
  }
  const handleDate = () =>{
    const dateTime = new Date().toLocaleString('en-GB')
    setDate(dateTime)
  }
  const handleFile = (e)=>{
    const fileObject = e.target.files[0]
    const fileUrl = URL.createObjectURL(fileObject)
    console.log("File URL", fileUrl)
    setFile(fileUrl)
    
  }

  const dateTime = new Date().toLocaleString('en-GB')

  const postData = () =>{
      const dataToSend = {
          name:"Anonymus",
          title:title,
          journalEntry:journalEntry,
          date:dateTime,
          file:file
      }
      console.log("DataToSend", dataToSend)
      Axios.post("http://localhost:5000/post", dataToSend).then((response)=>{
          alert("Journal Entry Submitted!")
          console.log("Post Data", response.data)
      })
      .catch((error)=>{console.log(error)})
  }
  /* End of Click Handlers */
    return(
        <main className ="post__main">
            <form onSubmit={(e)=>{e.preventDefault()}} className = "post__form">
                <input onChange={handleFile} type = "file"/>
                <input onChange={handleTitle} type = "text" placeholder= "Title"/>
                <input onChange={handleJournalEntry}type = "text" placeholder = "Journal Entry"/>
                <button onClick = {postData} className = "form__button">Submit Entry</button>
                <img className="post__image" url={file}/>
            </form>
            <button onClick={handleFileUpload}>Upload Image</button>
            <Link to = "/">Back to HomePage</Link>
        </main>
  )
}

提前谢谢大家!

在你的代码中,提交到服务器的文件是一个类似“blob://xxxxxxxxxxx”的字符串,
它对服务器端没有意义,
正确的代码:

const handleFile = (e)=>{
    setFile(e.target.files[0])
}
const fileURL = React.useMemo(()=> file && URL.createObjectURL(file), file);
// ...
<img src={fileURL} />

以及如何在 axios 中发送文件这是另一个问题 search