4
6

More than 5 years have passed since last update.

【echo】ファイルのアップロード方法で詰まった話

Posted at

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

4
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
6