Search code examples
gofilenamesmultipartenctype

Pass filename of the file selected for upload using enctype="multipart/form-data" to a struct field in Golang


My application uses the html code snippet for the form to upload a file

<form  method="POST" action="/addproduct" enctype="multipart/form-data">
        <label class="form-control-label" for="productimage"></label>
        {{with .Errors.image}}
        <div class="alert alert-danger">
            {{.}}
        </div>
        {{end}}     

        <input type="file" name="productimage" id = "productimage" multiple="multiple" class = "btn btn-danger">

        <input type="submit" name="submit" value="Submit" class = "btn btn-info">
    </form>

I need to grab the filename of the uploaded file and pass it to a struct field in Golang.

    file, header, err := r.FormFile("productimage")
    defer file.Close()
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
    var pimage = header.Filename 

p := &Product{
    Puid:     Puid(),
    Pname:    r.FormValue("productName"),
    Quantity: r.FormValue("quantity"),
    Price:    r.FormValue("price"),
    Image:    pimage,
}

I am trying to pass the name of the file selected for uploaded to 'image' field of the struct 'Product'. Any suggestions on how this can be done?


Solution

  • Instead of calling r.FormFile(), you could instead try:

    mpr, _ := r.MultipartReader()
    filePart, _ := r.NextPart()
    fileName := filePart.FileName()
    

    However, I would check the errors :)