使用Go将文件和文件夹上传到Box账户。

huangapple go评论82阅读模式
英文:

Uploading the files and folders using Go to the box account

问题

以下是您提供的代码的翻译:

对于下面的程序,我得到了以下错误。如果有人能帮助我修复错误,将非常有帮助。提前感谢。

func upload() {
    fmt.Println("dfxfgcghvjbjhiiiiiiiiiiiiiiiiiii")
    apiUrl := "https://upload.box.com/"
    resource := "api/2.0/files/content"
    data := url.Values{}
    data.Add("access_token", accessobj.Access_token)
    authbear := "Bearer "
    authbear += accessobj.Access_token
    
    u, _ := url.ParseRequestURI(apiUrl)
    u.Path = resource
    urlStr := fmt.Sprintf("%v", u)
    client := &http.Client{}
    fmt.Println(urlStr)
    
    f, err := ioutil.ReadFile("C:\\Users\\vembu\\Desktop\\hi.txt")
    ioutil.WriteFile("hi.txt", f, 0x777)
    r, _ := http.NewRequest("POST", urlStr, bytes.NewBuffer(f))
    r.Header.Add("Authorization", "Bearer "+accessobj.Access_token)
    r.Header.Add("attributes",
        "{\"name\":\"hi.txt\",\"parent\":{\"id\":\"3098791209\"}}")
    r.Header.Add("file", "hi.txt")
    fmt.Println(r)
    
    if err != nil {
        fmt.Println("error......:", err)
    }
    
    resp, err1 := client.Do(r)
    if err1 != nil {
        fmt.Println("error:", err1)
    }
    fmt.Println("uploading")
    fmt.Println(resp)
    
    re, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("errorrrrr:", err)
    }
    fmt.Println(string(re))
}

我得到了以下错误:

我遇到了 &{405 Method Not Allowed 405 HTTP/1.1 1 1 map[Allow:[GET, OPTIONS, HEAD] Content-Type:[text/html;charset=UTF-8] Content-Length:[0] Date:[Thu, 12 Mar 2015 13:07:32 GMT] Age:[0] Connection:[keep-alive] Server:[ATS]] 0xc08200b8c0 0 [] false map[] 0xc08201f2b0 0xc082060980}

英文:

For the program below I get the below error. It will be helpful if anyone helps me to fix my errors. Thanks in advance.

func upload() {
fmt.Println("dfxfgcghvjbjhiiiiiiiiiiiiiiiiiii")
apiUrl := "https://upload.box.com/"
resource := "api/2.0/files/content"
data := url.Values{}
data.Add("access_token", accessobj.Access_token)
authbear := "Bearer "
authbear += accessobj.Access_token
u, _ := url.ParseRequestURI(apiUrl)
u.Path = resource
urlStr := fmt.Sprintf("%v", u)
client := &http.Client{}
fmt.Println(urlStr)
f, err := ioutil.ReadFile("C:\\Users\\vembu\\Desktop\\hi.txt")
ioutil.WriteFile("hi.txt", f, 0x777)
r, _ := http.NewRequest("POST", urlStr, bytes.NewBuffer(f))
r.Header.Add("Authorization", "Bearer "+accessobj.Access_token)
r.Header.Add("attributes",
"{\"name\":\"hi.txt\",\"parent\":{\"id\":\"3098791209\"}}")
r.Header.Add("file", "hi.txt")
fmt.Println(r)
if err != nil {
fmt.Println("error......:", err)
}
resp, err1 := client.Do(r)
if err1 != nil {
fmt.Println("error:", err1)
}
fmt.Println("uploading")
fmt.Println(resp)
re, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("errorrrrr:", err)
}
fmt.Println(string(re))
}

I get the following error:

I face &{405 Method Not Allowed 405 HTTP/1.1 1 1
map[Allow:[GET, OPTIONS, HEAD] Content-Type:[text/html;charset=UTF-8]
Content-Length:[0] Date:[Thu, 12 Mar 2015 13:07:32 GMT] Age:[0]
Connection:[keep-alive]
Server:[ATS]] 0xc08200b8c0 0 [] false map[] 0xc08201f2b0 0xc082060980}

答案1

得分: 2

问题在于你尝试进行一个HTTP POST请求:

r, _ := http.NewRequest("POST", urlStr, bytes.NewBuffer(f))

但是服务器不允许/支持这样做,如响应错误中所述(只允许GETOPTIONSHEAD方法):

> Method Not Allowed 405 HTTP/1.1 1 1 map[Allow:[GET, OPTIONS, HEAD]

根据box.com API,要使用POST上传文件,你需要使用多部分表单上传请求。

你可以使用multipart包创建一个带有文件的多部分请求。

以下是一个示例代码(不完整/未经测试):

buf := &bytes.Buffer{}
mw := multipart.NewWriter(buf)
defer mw.Close()
f, err := os.Open("C:\\Users\\vembu\\Desktop\\hi.txt")
if err != nil {
// 处理错误
}
defer f.Close()
ff, err := mw.CreateFormFile("name", "hi.txt")
if err != nil {
// 处理错误
}
if _, err = io.Copy(ff, f); err != nil {
// 处理错误
}
// TODO: 在URL中包含其他字段/参数
r, err := http.NewRequest("POST", "https://upload.box.com/api/2.0/files/content", buf)
if err != nil {
// 处理错误
}
r.Header.Set("Content-Type", mw.FormDataContentType())
// TODO: 添加其他头字段
// 发起调用:上传文件
client := &http.Client{}
resp, err := client.Do(r)
if err != nil {
// 处理错误
}
if resp.StatusCode != http.StatusOK {
fmt.Printf("错误:%v", resp.Status)
}
英文:

The problem is that you try to do an HTTP POST request:

r, _ := http.NewRequest("POST", urlStr, bytes.NewBuffer(f))

But the server does not allow/support this as stated in the response error (only GET, OPTIONS and HEAD methods are allowed):

> Method Not Allowed 405 HTTP/1.1 1 1 map[Allow:[GET, OPTIONS, HEAD]

According to the box.com API to upload a file using POST you need to use a multi-part form upload request.

You can use the multipart package to create a multipart request with a file.

Here is an example how to do it (incomplete/untested code):

buf := &bytes.Buffer{}
mw := multipart.NewWriter(buf)
defer mw.Close()
f, err := os.Open("C:\\Users\\vembu\\Desktop\\hi.txt")
if err != nil {
// Handle error
}
defer f.Close()
ff, err := mw.CreateFormFile("name", "hi.txt")
if err != nil {
// Handle error
}
if _, err = io.Copy(ff, f); err != nil {
// Handle error
}
// TODO: INCLUDE OTHER FIELDS/PARAMS IN URL
r, err := http.NewRequest("POST", "https://upload.box.com/api/2.0/files/content", buf)
if err != nil {
// Handle error
}
r.Header.Set("Content-Type", mw.FormDataContentType())
// TODO: ADD YOUR OTHER HEADER FIELDS
// Do the call: upload file
client := &http.Client{}
resp, err := client.Do(r)
if err != nil {
// Handle error
}
if resp.StatusCode != http.StatusOK {
fmt.Printf("Error: %v", resp.Status)
}

huangapple
  • 本文由 发表于 2015年5月11日 13:58:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/30160508.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定