Skip to content

Instantly share code, notes, and snippets.

@CaiJingLong
Created November 8, 2018 10:05
Show Gist options
  • Save CaiJingLong/c00b7e56ccccd36a9e2cfed2bb811b22 to your computer and use it in GitHub Desktop.
Save CaiJingLong/c00b7e56ccccd36a9e2cfed2bb811b22 to your computer and use it in GitHub Desktop.
upload file
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
)
func main() {
postUrl := "https://img.zku.me/upload.php?key=2bA0IPSeXgQfrZDsyV4BtY1X74ejhZWv"
// postUrl = "http://localhost:8080/api/test"
filePath := "/Users/cai/Desktop/test.png"
request, _ := newfileUploadRequest(postUrl, map[string]string{"key": "2bA0IPSeXgQfrZDsyV4BtY1X74ejhZWv"}, "file", filePath)
fmt.Println(request.Header)
fmt.Println(request.Body)
response, _ := http.DefaultClient.Do(request)
msg, _ := ioutil.ReadAll(response.Body)
fmt.Printf("结果 %s\n", msg)
}
func newfileUploadRequest(uri string, params map[string]string, paramName, path string) (*http.Request, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile(paramName, path)
if err != nil {
return nil, err
}
_, err = io.Copy(part, file)
for key, val := range params {
_ = writer.WriteField(key, val)
}
err = writer.Close()
if err != nil {
return nil, err
}
request, err := http.NewRequest("POST", uri, body)
request.Header.Set("Content-Type", writer.FormDataContentType())
return request, err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment