5

In my use case I am trying to upload a file to server in golang. I have the following html code,

<div class="form-input upload-file" enctype="multipart/form-data" >
    <input type="file"name="file" id="file" />
    <input type="hidden"name="token" value="{{.}}" />
    <a href="/uploadfile/" data-toggle="tooltip" title="upload">
        <input type="button upload-video" class="btn btn-primary btn-filled btn-xs" value="upload" />
    </a>
</div>

And the server side,

func uploadHandler(w http.ResponseWriter, r *http.Request) {
    // the FormFile function takes in the POST input id file
    file, header, err := r.FormFile("file")
    if err != nil {
        fmt.Fprintln(w, err)
        return
    }
    defer file.Close()

    out, err := os.Create("/tmp/uploadedfile")
    if err != nil {
        fmt.Fprintf(w, "Unable to create the file for writing. Check your write access privilege")
        return
    }
    defer out.Close()

    // write the content from POST to the file
    _, err = io.Copy(out, file)
    if err != nil {
        fmt.Fprintln(w, err)
    }

    fmt.Fprintf(w, "File uploaded successfully : ")
    fmt.Fprintf(w, header.Filename)
}

When I try to upload the file, I am getting request Content-Type isn't multipart/form-data error in server side.

Could anyone help me on this?

Dany
  • 2,692
  • 7
  • 44
  • 67

2 Answers2

3

To be honest I have no idea how do you even get error as your HTML is not form. But I think you getting error because by default form is send as GET request while multipart/form-data should be send via POST. Here is example of minimal form which should work.

<form action="/uploadfile/" enctype="multipart/form-data" method="post">
    <input type="file" name="file" id="file" />
    <input type="hidden"name="token" value="{{.}}" />
    <input type="submit" value="upload" />
</form>
CrazyCrow
  • 4,125
  • 1
  • 28
  • 39
  • Thank you. I am trying to use this inside another form. so I tried that way. Is there any work around to use this inside another form? It would be very helpful – Dany Mar 06 '16 at 12:21
  • @DineshAppavoo Form inside form? – CrazyCrow Mar 06 '16 at 12:22
  • looks like it is not possible [nest-forms](http://stackoverflow.com/questions/379610/can-you-nest-html-forms). I tried, the original form is getting collapsed. Is there any workaround for this? – Dany Mar 06 '16 at 20:41
  • 1
    @DineshAppavoo only one "workaround" that I can imagine is send files via AJAX and put their IDs into "parent" form. But I can't understand why do you need nested form at all if you can just send one with fields and files. – CrazyCrow Mar 07 '16 at 07:30
0

The issue is that you must include the header that contains the content type.

req.Header.Add("Content-Type", writer.FormDataContentType())

This is included in the mime/multipart package.

For a working example please check this blog post.

Endre Simo
  • 11,330
  • 2
  • 40
  • 49