// PostFormDataAndFile 提交头像到远程服务器
func PostFormDataAndFile(projectID, uuid string) (string, error) {
client := http.Client{}
bodyBuf := &bytes.Buffer{}
defineConfig := global.GetConfig("define")
postUrl := defineConfig.GetString("IMG_AVATAR_URL_" + projectID)
imgPath := defineConfig.GetString("AVATAR_PATH")
imageFilePath := imgPath + projectID + "-" + uuid + ".jpg"
bodyWrite := multipart.NewWriter(bodyBuf)
file, openErr := os.Open(imageFilePath)
if openErr != nil {
return "Open Error", openErr
}
defer file.Close()
bodyWrite.WriteField("authKey", "*******")
bodyWrite.WriteField("uuid", uuid)
fileWrite, _ := bodyWrite.CreateFormFile("imgFile", uuid+".jpg")
_, copyErr := io.Copy(fileWrite, file)
if copyErr != nil {
return "Copy Error", copyErr
}
bodyWrite.Close()
contentType := bodyWrite.FormDataContentType()
req, newRequestErr := http.NewRequest(http.MethodPost, postUrl+"appimg/setAvatar.php", bodyBuf)
if newRequestErr != nil {
return "NewRequest Error", newRequestErr
}
req.Header.Set("Content-Type", contentType) // 设置头
resp, doErr := client.Do(req)
if doErr != nil {
return "Do Error", doErr
}
defer resp.Body.Close()
result, readAllErr := ioutil.ReadAll(resp.Body)
if readAllErr != nil {
return "ReadAll Error", readAllErr
}
if removeErr := os.Remove(imageFilePath); removeErr != nil {
return "Remove Error", removeErr
}
return string(result), nil
}
Go-POST提交图片文件&参数到远程服务器
最新推荐文章于 2022-12-17 20:27:33 发布