GO上传文件给PHP,第一篇文章里面少了个request.Header.Set(“Content-Type”, formcontenttype) 希望能够帮助别人
func upimgAction(imgurl string, url string) { path := imgurl extraParams := map[string]string{ "param1": "1", "param2": "2", "param3": "3", } request, err := newfileUploadRequest(url, extraParams, "Filedata", path)//Filedata文件名称 if err != nil { log.Error(err) } //fmt.Println(request) resp, err := Gclient.Do(request) if err != nil { log.Error(err) } else { body := &bytes.Buffer{} _, err := body.ReadFrom(resp.Body) if err != nil { log.Error(err) } resp.Body.Close() //fmt.Println(resp.StatusCode) //fmt.Println(resp.Header) fmt.Println(body) } } 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) for key, val := range params { _ = writer.WriteField(key, val) } formcontenttype := writer.FormDataContentType() part, err := writer.CreateFormFile(paramName, filepath.Base(path)) if err != nil { return nil, err } _, err = io.Copy(part, file) err = writer.Close() if err != nil { return nil, err } //fmt.Println(body) request, err := http.NewRequest("POST", uri, body) request.Header.Set("Content-Type", formcontenttype) return request, err }
参考网站 http://matt.aimonetti.net/posts/2013/07/01/golang-multipart-file-upload-example/
http://stackoverflow.com/questions/20205796/golang-post-data-using-the-content-type-multipart-form-data
有疑问加站长微信联系(非本文作者)