I create react app that use API created with Spring Boot.
I would like to send a file to the server via the form in my react app (The server works good because I can upload file in Postman).
This is my form:
<form onSubmit={e => uploadFile(e)} >
<input type="file" name="img" onChange={changeHandler} />
<button>Add!</button>
</form>
uploadFile
and changeHandler
methods:
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])
}
When I submit this form I get this:
Fetch API cannot load localhost:8080/courses/18/comments/1/img. URL scheme "localhost" is not supported.
How to solve this problem ?
You have to specify the URL as follows.
http://localhost:8080/courses/1/comments/1/img
You might be forgot to specify the http protocol in the URL.
So, replace localhost:8080/courses/1/comments/1/img
in the fetch method with http://localhost:8080/courses/1/comments/1/img
fetch(`http://localhost:8080/courses/1/comments/1/img`, {
method: 'post',
body: formData
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With