golang 使用form上传文件
// import github.com/fwhezfwhez/errorx
func GenerateFileAndUpload(filePath string, url string, args map[string]string, resp interface{}) error {
bodyBuffer := &bytes.Buffer{}
bodyWriter := multipart.NewWriter(bodyBuffer)
info, e := os.Stat(filePath)
if e == os.ErrNotExist {
return errorx.NewFromStringf("file %s not exist", filePath)
}
if info.IsDir() {
return errorx.NewFromStringf("path %s is a directory not a file", filePath)
}
fileWriter1, e := bodyWriter.CreateFormFile("file", info.Name())
if e != nil {
return errorx.Wrap(e)
}
fmt.Println("fileName", info.Name())
file1, e := os.Open(filePath)
if e != nil {
return errorx.Wrap(e)
}
defer file1.Close()
_, e = io.Copy(fileWriter1, file1)
if e != nil {
return errorx.Wrap(e)
}
for key, value := range args {
e = bodyWriter.WriteField(key, value)
if e != nil {
return errorx.Wrap(e)
}
}
contentType := bodyWriter.FormDataContentType()
bodyWriter.Close()
req, e := http.NewRequest("POST", url, bodyBuffer)
if e != nil {
return errorx.Wrap(e)
}
req.Header.Set("Content-Type", contentType)
res, e := c.Do(req)
if e != nil {
return errorx.Wrap(e)
}
if res == nil {
return errorx.NewFromString("resp nil")
}
if res.Body == nil {
return errorx.NewFromString("response.body nil")
}
defer res.Body.Close()
buf, e := ioutil.ReadAll(res.Body)
if e != nil {
return errorx.Wrap(e)
}
if res.StatusCode != 200 {
if len(buf) > 200 {
return errorx.NewFromStringf("recv status %d, body \n%s", res.StatusCode, buf[:199])
} else {
return errorx.NewFromStringf("recv status %d, body \n%s", res.StatusCode, buf)
}
}
if e := json.Unmarshal(buf, resp); e != nil {
if len(buf) > 200 {
return errorx.NewFromStringf("marshal error '%v', body '%s'", e, buf[:199])
}
return errorx.NewFromStringf("marshal error '%v', body '%s'", e, buf)
}
return nil
}