Recently I started working with Go to make servers, in my current experiment I am trying to upload an image to my Go/mux webserver via fetch on a React.js front-end. Whenever I upload an image through a form the server fails to receive the image and returns a "no such file" error. I am using JS's FormData API to store and send the image.
Here is the code for the client
handleInput = (e) => {
let formData = new FormData();
formData.append("myImage", e.target.files)
fetch("http://localhost:8080/api", {
method: 'POST',
body: formData,
})
.then((res) => {
console.log(res)
})
.then(() => {
console.log("Success")
})
.catch((error) => console.error(error))
}
Here is the code for the server
func api(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
fmt.Println("Connected -> api route")
fmt.Fprintf(w, "connected to api")
// ERROR HERE: no such file / failed to retrieve image
r.ParseMultipartForm(32 << 20)
file, _, err := r.FormFile("myImage")
if err != nil {
log.Print(err)
fmt.Println("failed to retrieve image")
w.WriteHeader(http.StatusBadRequest)
return
} else if err == nil {
fmt.Println("Success")
}
defer file.Close()
}
I have tried adding and removing the multipart/form-data headers, neither have worked.
I'm new to Go and still trying to figure things out, any help is appreciated!
Checking the code, this is a pretty standard upload file method, is your Go api working with other services?, I can not find anything wrong, so maybe is more about how the api is configured in general.
Other thing you can do is handling the error at
if err := r.ParseMultipartForm(32 << 20); err != nil {
fmt.Println(err)
}
maybe you can have a better idea about the error
Also make sure your file is really there before appending it
console.log(e.target.files)