在做discord bot开发时,有将discord聊天框中的图片下载袭来,并通过http转发出去的需求,以下是对应的代码,需要注意的是,因为是在国内网,通过http消息下载国外网络需要设置代理:
func uploadFile(token, fileUrl, name string) (string, error){
// 设置代理
proxy := func(_ *http.Request) (*url.URL, error) {
return url.Parse("http://127.0.0.1:7890")
}
transport := &http.Transport{Proxy: proxy}
client := &http.Client{Transport: transport}
resp, err := client.Get(fileUrl)
fmt.Println(fileUrl)
if err != nil {
panic(err)
return "", err
}
defer resp.Body.Close()
contentType := resp.Header.Get("Content-Type")
fmt.Println(contentType)
if !strings.Contains(contentType, "image") {
return "", errors.New("only support to upload images")
}
//将下载到的文件写入buffer中并创建request
bodyBuffer := &bytes.Buffer{}
bodyWriter := multipart.NewWriter(bodyBuffer)
fileWriter, _ := bodyWriter.CreateFormFile("file", name)
io.Copy(fileWriter, resp.Body)
contentType1 := bodyWriter.FormDataContentType()
bodyWriter.Close()
req, _ := http.NewRequest("POST", viper.GetString("fileUploadUrl"), bodyBuffer)
fmt.Println(req)
req.Header.Add("Authorization", "Bearer " + token)
req.Header.Add("content-type", contentType1)
fmt.Println(contentType1)
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return "", err
}
var t models.UploadFilesResponse
err = json.Unmarshal(body, &t)
if err != nil {
return "", err
}
fmt.Println(t.FileUrl)
return t.FileUrl, nil
}