dpka7974 2016-02-05 07:42
浏览 41

将图像作为POST请求中的主体附加到golang服务器

I have a local golang server with an endpoint that listens to POST requests, decodes the body of the request, and persists it. This works when I manually curl the endpoint like

    curl -X POST localhost:8080/newimage --data-binary "PATH"

However, I'm having trouble successfully uploading a file in a POST request through a gui I'm working on. I'm using https://github.com/okonet/react-dropzone to drop a File and appending it to a FormData object, but the golang server does not seem to be receiving a populated body.

This is how I'm creating the AJAX query:

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

And the backend server:

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
}

Would appreciate any suggestions.

  • 写回答

1条回答 默认 最新

  • dongtang1944 2016-02-05 10:51
    关注

    FormData is very different from sending the image as raw bytes. Here is an example on how to get the files from a multipart/form-data request:

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

    See https://golang.org/pkg/net/http/#Request.FormFile

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?