我正在尝试使用Soundcloud API(https://developers.soundcloud.com/docs/api/reference#tracks)将音频文件上传到Soundcloud。我必须传递文件的参数需要“音频文件的二进制数据”,我不确定如何在Go中加载这样的东西。
我目前的代码如下,但音频文件当然无法正常发送。
buf := new(bytes.Buffer)
w := multipart.NewWriter(buf)
label, err := w.CreateFormField("oauth_token")
if err != nil {
return err
}
label.Write([]byte(c.Token.AccessToken))
fw, err := w.CreateFormFile("upload", "platform/young.mp3")
if err != nil {
return err
}
fd, err := os.Open("platform/young.mp3")
if err != nil {
return err
}
defer fd.Close()
_, err = io.Copy(fw, fd)
if err != nil {
return err
}
w.Close()
req, err := http.NewRequest("POST", "https://api.soundcloud.com/tracks.json", buf)
if err != nil {
return err
}
req.Header.Set("Content-Type", w.FormDataContentType())
req.SetBasicAuth("email@email.com", "password")
fmt.Println(req.Form)
res, err := c.Client.Do(req)
if err != nil {
return err
}
答案 0 :(得分:1)
我没有测试下面的代码,因为我没有有效的Oauth令牌,但它可能会让你走上正轨。
package main
import (
"bytes"
"fmt"
"io"
"log"
"mime/multipart"
"net/http"
"os"
"path/filepath"
)
func main() {
uri := "https://api.soundcloud.com/tracks.json"
params := map[string]string{
"oauth_token": "************",
"track[title]": "Test Track",
"track[sharing]": "public",
}
trackData := "track[asset_data]"
path := "test_track.mp3"
file, err := os.Open(path)
if err != nil {
log.Fatal(err)
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile(trackData, filepath.Base(path))
if err != nil {
log.Fatal(err)
}
_, err = io.Copy(part, file)
for key, val := range params {
err := writer.WriteField(key, val)
if err != nil {
log.Fatal(err)
}
}
err = writer.Close()
if err != nil {
log.Fatal(err)
}
request, err := http.NewRequest("POST", uri, body)
if err != nil {
log.Fatal(err)
}
request.Header.Set("Content-Type", writer.FormDataContentType())
client := &http.Client{}
resp, err := client.Do(request)
if err != nil {
log.Fatal(err)
} else {
body := &bytes.Buffer{}
_, err := body.ReadFrom(resp.Body)
if err != nil {
log.Fatal(err)
}
resp.Body.Close()
fmt.Println(resp.StatusCode)
fmt.Println(resp.Header)
fmt.Println(body)
}
}