You might see that the Dropbox Community team have been busy working on some major updates to the Community itself! So, here is some info on what’s changed, what’s staying the same and what you can expect from the Dropbox Community overall.

Forum Discussion

fenario's avatar
fenario
Explorer | Level 3
7 years ago

golang file upload

Hi,

 

I was able to upload a file using golang using this:

 

var (
            body = &bytes.Buffer{}
            writer = multipart.NewWriter(body)
        )
        b := dropboxAPI{
            Path: "/" + name,
            Mode: "add",
            Autorename: true,
            Mute: false,
        }
        header, err := json.Marshal(b)
        if err != nil {
            return nil, errors.New(fmt.Errorf("json marshal, err: %#v", err).Error())
        }

        resolvedURL, err := url.Parse(c.dbclient.ContentURL.String() + "/2/files/upload")
        if err != nil {
            fmt.Println(err)
        }

        p, err := writer.CreateFormFile("file", name)
        if err != nil {
            return nil, errors.New(fmt.Errorf("multipart creatformfile, err: %#v", err).Error())
        }
        _, err = io.Copy(p, r)
        //writer.WriteField("data-binary", name)
        err = writer.Close()
        if err != nil {
            return nil, errors.New(fmt.Errorf("multipart close, err: %#v", err).Error())
        }

        req, err := http.NewRequest(http.MethodPost, resolvedURL.String(), body)
        //add headers for dropbox
        req.Header.Add("Content-Type", writer.FormDataContentType())
        req.Header.Add("Content-Type", "application/octet-stream")
        req.Header.Add("Dropbox-API-Arg", string(header))
        req.Header.Add("Cache-Control", "no-cache")
        if err != nil {
            return nil, errors.New(fmt.Errorf("new http request failed, resp: %#v", req).Error())
        }
        fmt.Println("Req: ", req.Header)

        var data File
        _, err = c.dbclient.Do(req, &data)
        if err != nil {
            return nil, err
        }
 
However, when I download the file, the http headers were added to the file. Please see the image (upper right side). What could be causing this problem? Thanks
 
 
 
 
  • Greg-DB's avatar
    Greg-DB
    Icon for Dropbox Staff rankDropbox Staff
    It looks like the HTTP headers were incorrectly added to the file data. First, I recommend determining if this happened during your upload, or your download.

    The headers in the screenshot you shared don't seem to match the headers in your upload code, so I suspect the issue using occurring during the download. Are you using custom code to download the file, e.g., as opposed to downloading manually via the web site? If you're downloading via code, it may be good to download from the web site to compare.

    In either case, we can't offer help with using whatever third party HTTP client you're using in Go, so you may want to refer to its documentation.

    When uploading, the file data should be passed in the HTTP request body, so you'll need to make sure that the HTTP request is properly formatted, with the headers properly separated from the body, and not included in the body itself.

    When downloading, the file data is returned in the HTTP response body. When saving the file, you should make sure you only save the response body, and not the response headers. Most HTTP clients offer an easy way to do this, but you may need to refer to the client's documentation to be sure.
    • fenario's avatar
      fenario
      Explorer | Level 3

      I'm manually downloading. So, its definitely in the uploading process. I will look into this further. Thanks for the help 

  • DV2811's avatar
    DV2811
    New member | Level 2

    The content of the uploaded file should not be part of a multipart request.

    An example:

    package main
    import (
    "net/http"
    "strings"
    "fmt"
    "io"
    )
    var client = &http.Client{}
    func Upload(body io.Reader, filepath string) (string, error){
    req, err := http.NewRequest("POST", "https://content.dropboxapi.com/2/files/upload", body)
    if err != nil{
    return "Could not create new requests", err
    }
    dbx_args := fmt.Sprintf("{\"autorename\":true,\"mode\":\"overwrite\",\"mute\":true,\"path\":\"%s\",\"strict_conflict\":false}", filepath)
    req.Header = map[string][]string{
    "Authorization":{"Bearer <YOUr-TOKEN-HERE>"},
    "Content-Type": {"application/octet-stream"},
    "Dropbox-API-Arg" : {dbx_args},
    }
    res, err := client.Do(req)
    if err != nil{
    return "Failure to connect", err
    }
    status_code := res.StatusCode
    if status_code != 200{
    return "Upload failed", fmt.Errorf("%d", status_code)
    }
    return "OK",nil

    }
    func main(){
    file_content := strings.NewReader("Some file content")
    filepath := "/Folder/test_file.txt"
    msg, err := Upload(file_content, filepath)
    if err != nil{
    fmt.Println(err)
    } else{
    fmt.Println(msg)
    }
    }