我有一个带有端点的本地 golang 服务器,该端点监听 POST 请求、解码请求的主体并保存它。这在我像
这样手动 curl 端点时有效 curl -X POST localhost:8080/newimage --data-binary "PATH"
但是,我无法通过正在处理的 gui 在 POST 请求中成功上传文件。我正在使用 https://github.com/okonet/react-dropzone放下File并将其附加到 FormData 对象,但 golang 服务器似乎没有收到填充的主体。
这就是我创建 AJAX 查询的方式:
formData = new FormData();
formData.append("image", file)
$.ajax({
url: "http://localhost:8080/items/81d648b0-25f9-434e-9129-fe52575865dd/newimage",
type: "POST",
data: formData,
processData: false
}).done(function(res) {
console.log(res);
});
和后端服务器:
func (h *ItemHandler) PostImage(resp http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
itemID := vars["id"]
assetID := newAssetID()
// verify image
img, _, err := image.Decode(req.Body)
if err != nil {
log.Printf("could not decode body into an image")
resp.Header().Add("Access-Control-Allow-Origin", "*")
resp.WriteHeader(http.StatusBadRequest)
resp.Write([]byte("could not decode body image"))
return
}
如有任何建议,我们将不胜感激。
最佳答案
FormData 与将图像作为原始字节发送非常不同。 下面是一个关于如何从 multipart/form-data 请求中获取文件的示例:
func (h *ItemHandler) PostImage(resp http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
itemID := vars["id"]
assetID := newAssetID()
file, _, err := req.FormFile("image")
if err != nil{
log.Print(err)
resp.WriteHeader(http.StatusBadRequest)
return
}
// verify image
img, _, err := image.Decode(file)
if err != nil {
log.Printf("could not decode body into an image")
resp.Header().Add("Access-Control-Allow-Origin", "*")
resp.WriteHeader(http.StatusBadRequest)
resp.Write([]byte("could not decode body image"))
return
}
...
}
关于javascript - 将图像作为正文附加到 golang 服务器的 POST 请求中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35218732/