goでファイルをアップロードさせるやり方を調べると大体こんな感じのソースが出てくると思います。
func UploadFile(w http.ResponseWriter, r *http.Request) {
upload_file, _, err := r.FormFile("input_name")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer upload_file.Close()
dst_file, err := os.Create("/tmp/tmp.txt")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer dst_file.Close()
io.Copy(dst_file, upload_file)
http.Redirect(w, r, "/show", http.StatusFound)
}
リクエストからアップロードするファイルをハンドリングしているのですが、
echoのコントローラの場合はリクエストを c echo.Context で扱うため上記のままだと上手くいきません。
func UploadCsv(c echo.Context) error {
upload_file, err := c.FormFile("input_name")
if err != nil {
return err
}
src, err := upload_file.Open()
if err != nil {
return err
}
defer src.Close()
dst_file, err := os.Create("./tmp/tmp.txt")
if err != nil {
return err
}
defer dst_file.Close()
if _, err = io.Copy(dst_file, src); err != nil {
return err
}
return c.JSON(http.StatusOK, "file has uploaded")
}
c.Formfile()に対してOpen()メソッドを使いio.Readerオブジェクトに変換する必要があるみたいです。
参考
File Upload Recipe | Echo - High performance, minimalist Go web framework