I'm building a webserver (in Go) as a personal project and currently struggling trying to implement an image upload feature.
This is the code of the HTTP handler:
r.Body = http.MaxBytesReader(w, r.Body, MAX_SIZE)
if err := r.ParseMultipartForm(MAX_SIZE); err != nil{
util.ReturnBadRequest(w)
fmt.Println("file too big: $s", err.Error())
return
}
file, handler, err := r.FormFile("banner")
if err != nil{
fmt.Println(err)
http.Error(w, "Unable to parse image", http.StatusBadRequest)
return
}
fmt.Println("file accepted")
dst, err := os.Create(fmt.Sprintf("./tmp/images/%s", handler.Filename))
if err != nil{
panic(err)
}
io.Copy(dst, file)
r.Body.Close()
This code works fine as long as the file size is under 500KB or so. With larger files I get no response at first and then after a few seconds a: net::ERR_CONNECTION_RESET (in Firefox it's: NetworkError when attempting to fetch resource). The MAX_SIZE constant is currently set to 20 << 20, but I've tried all kinds of values. I've tried adding the MaxBytesReader (which I didn't have at first) after some research but that made no difference.
I'm not sure if this is being caused on the backend or the frontend (React). the frontend code is simply this:
const fd = new FormData();
fd.append("banner", image);
const response = await fetch(url, {
method: "POST",
body: fd,
});
I've also tried to send the request from Postman. From there it does reach the handler but I get a multipart: NextPart: EOF error from the ParseMultipartForm call even though the file is smaller than the max size I specified in the handler.
The same problem occurs in both Chrome and Firefox.
I can't figure out where the problem lies. It could be that the request from the browser times out before it finishes parsing the relatively large file but I haven't set a maximum on that.
Does anyone know what's causing this?