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 ?

6

2 Answers

You have to specify the URL as follows.

 

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

fetch(` { method: 'post', body: formData }) 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.