最近我开始使用 Go 来制作服务器,在我目前的实验中,我试图通过在 React.js 前端上获取图像将图像上传到我的 Go/mux 网络服务器。每当我通过表单上传图像时,服务器无法接收图像并返回“没有这样的文件”错误。我正在使用 JS 的 FormData API 来存储和发送图像。
这是客户端的代码
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))
}
这是服务器的代码
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()
}
我已经尝试添加和删除 multipart/form-data header ,但都没有用。
我是 Go 的新手,仍在尝试解决问题,感谢任何帮助!
最佳答案
检查代码,这是一个非常标准的上传文件方法,你的 Go api 是否与其他服务一起工作?,我找不到任何错误,所以可能更多的是关于 api 的一般配置方式。
您可以做的另一件事是处理
处的错误if err := r.ParseMultipartForm(32 << 20); err != nil {
fmt.Println(err)
}
也许你可以对错误有更好的了解
在追加之前还要确保你的文件确实存在
console.log(e.target.files)
关于javascript - 无法将图像发送到 Go 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56093629/