我希望用戶應該能夠上傳任何影像。
下面的代碼為我提供了 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>
)
}
提前謝謝大家!
uj5u.com熱心網友回復:
在你的代碼中,檔案提交到服務器是一個像“blob://xxxxxxxxxxx”
這樣的字串,它對服務器端沒有意義,
正確的代碼:
const handleFile = (e)=>{
setFile(e.target.files[0])
}
const fileURL = React.useMemo(()=> file && URL.createObjectURL(file), file);
// ...
<img src={fileURL} />
以及如何在 axios 中發送檔案這是另一個問題 搜索
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/335644.html
