POST data using the Content-Type multipart/form-data

后端 未结 7 1448
小鲜肉
小鲜肉 2020-11-27 12:16

I\'m trying to upload images from my computer to a website using go. Usually, I use a bash script that sends a file and a key to the server:

curl -F \"image         


        
7条回答
  •  一整个雨季
    2020-11-27 13:18

    Had the same issue in a unit test, and if you just need to send in a data to verify that the post this (below) was a little simpler for me. Hope it helps save someone else some time.

    fileReader := strings.NewReader("log file contents go here")
    b := bytes.Buffer{} // buffer to write the request payload into
    fw := multipart.NewWriter(&b)
    fFile, _ := fw.CreateFormFile("file", "./logfile.log")
    io.Copy(fFile, fileReader)
    fw.Close()
    
    req, _ := http.NewRequest(http.MethodPost, url, &b)
    req.Header.Set("Content-Type", fw.FormDataContentType())
    resp, err := http.DefaultClient.Do(req)
    assert.NoError(t, err)
    assert.Equal(t, http.StatusOK, resp.StatusCode)
    

    For me, fileReader is just a strings reader, because I'm posting a log file. In the case of a image, you would send the appropriate reader.

提交回复
热议问题