Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
6
Help us understand the problem. What is going on with this article?
@witchy

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

More than 3 years have passed since last update.

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

6
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
witchy
e-grant
EC・通販に特化したCRMツール「うちでのこづち」を中心に、CRM関連のビックデータ・AI系の開発・運営を行なっています。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
6
Help us understand the problem. What is going on with this article?