26

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
    You forgot the scheme (http or https) Commented Sep 15, 2021 at 19:14
  • Yes... Should I delete this questiuon ? Commented Sep 15, 2021 at 19:27
  • I think you should Commented Sep 15, 2021 at 19:31
  • 6
    I don't know, I had an error that got me here and I was just forgetting to connect with a prototcol, so this was a useful question for me. Commented Jan 12, 2023 at 19:37
  • 1
    @Monoxyd I also came here via searching for the same error, and it solved my problem. Why on earth would you want to delete such a question? What is the purpose of stackoverflow, if not for questions like this? Commented Mar 30, 2023 at 4:03

2 Answers 2

57

You have to specify the URL as follows.

http://localhost:8080/courses/1/comments/1/img
Sign up to request clarification or add additional context in comments.

Comments

11

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
})

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.