从表单导入CSV文件并使用GO解析结果

时间:2014-06-06 06:00:29

标签: forms csv web go

所以我试图导入一个我从excel转换过的csv文件,它有两列问题和答案。我只想解析文件并将其打印到控制台。当我选择我的文件sample.csv时,它只是退出1并说找不到文件。任何帮助都将是一个很大的帮助。

HTML

   <form class="form-horizontal" method="post" action="/deck/{{ .deck.Id }}/bulkimport" >
           <div class="form-group">
          <div class="col-lg-10">
              <div class="alert alert-info">
                    <input type="file" name="file" style="visibility: hidden;" id="pdffile"/>
                    <label>Choose A File</label>
                    <div class="input-append">
                    <input type="text" id="subfile" class="input-xlarge"/>
                    <a class="btn" onclick="$('#pdffile').click();">Browse</a>
                    </div>
                    <br/>
                  <!--   <button id="showHidden" class="btn btn-warning">Show/Hide Input Field</button> -->
                    <input name="deck" value="{{.deck.Id}}" hidden> 
                    <button class="btn btn-primary" type="submit" name="submit">Upload</button>
                    </div>
              </div>
            </div>
      </form>

GO FUNCTION

func BulkImortFlashCardsFormPage (req *http.Request, params martini.Params, c Flashcard,errors binding.Errors, r render.Render,session sessions.Session, db *DB) {
     id := params["id"]
     f, _, err := req.FormFile("file")
     if err != nil {
         // log.Fatal("Can't Find File ")
         session.AddFlash(FlashError {"global", "File not found", "", "error"})
         r.Redirect("/deck/" + id + "/cardlist")
         return
     }
    defer f.Close()
    reader := csv.NewReader(f)
    record, err := reader.ReadAll()
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    for _, line := range record {
        fmt.Println(line[1]) 
    }
    session.AddFlash(FlashError {"global", "Cards created succesfully", "", "success"})
    r.Redirect("/deck/" + id + "/cardlist")
    return
    }

1 个答案:

答案 0 :(得分:1)

错误在于您的HTML表单根本没有发送文件:因此您需要在表单标记上声明enctype="multipart/form-data"属性。像那样:

<form method="post" action="/deck/{{ .deck.Id }}/bulkimport" enctype="multipart/form-data">
    […]
</form>