我创建了使用 Spring Boot 创建的 API 的 React 应用程序。
我想通过我的反应应用程序中的表单将文件发送到服务器(服务器运行良好,因为我可以在 Postman 中上传文件)。
这是我的表格:
<form onSubmit={e => uploadFile(e)} >
<input type="file" name="img" onChange={changeHandler} />
<button>Add!</button>
</form>
Run Code Online (Sandbox Code Playgroud)
uploadFile和changeHandler方法:
const [selectedFile, setSelectedFile] = useState()
const uploadFile = () => {
const formData = new FormData()
formData.append('File', selectedFile)
fetch(`localhost:8080/courses/1/comments/1/img`, {
method: 'post',
body: formData
})
.then(resp => resp.json())
.then(data => console.log(data))
.catch(err => console.log(err))
}
const changeHandler = (e) => {
setSelectedFile(e.target.files[0])
}
Run Code Online (Sandbox Code Playgroud)
当我提交此表格时,我得到以下信息:
Fetch API cannot load localhost:8080/courses/18/comments/1/img. URL scheme "localhost" …Run Code Online (Sandbox Code Playgroud)