3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Goでファイルアップロードアプリを作る

3
Last updated at Posted at 2020-07-23

ディレクトリ構成

imgフォルダにアップロードしたファイルが保存されます。

./
 ├ index.html
 ├ main.go
 ├ img/
   └ ここにファイルが保存される
   └ ここにファイルが保存される
   └ ここにファイルが保存される
             .
               .
               .
               .
   

コード

main.go

main.go
package main

import (
	"html/template"
	"io"
	"log"
	"net/http"
	"os"
)

func upload(w http.ResponseWriter, r *http.Request) {
	//メソッドをPOSTのみ許可
	if r.Method != "POST" {
		log.Fatal("許可されていないメソッド")
	}

	//formから送信されたファイルを解析
	file, fileHeader, err := r.FormFile("image")
	if err != nil {
		log.Fatal("ファイルのアップロード失敗")
	}
	//アップロードされたファイル名を取得
	uploadedFileName := fileHeader.Filename
	//アップロードされたファイルを置くパスを設定
	imagePath := "img/" + uploadedFileName

	//imagePathにアップロードされたファイルを保存
	saveImage, err := os.Create(imagePath)
	if err != nil {
		log.Fatal("ファイルの確保失敗")
	}

	//保存用ファイルにアップロードされたファイルを書き込む
	_, err = io.Copy(saveImage, file)
	if err != nil {
		log.Fatal("アップロードしたファイルの書き込み失敗")
	}

	//saveImageとfileを最後に閉じる
	defer saveImage.Close()
	defer file.Close()

	//もう1周
	http.Redirect(w, r, "/", 302)
}

func index(w http.ResponseWriter, r *http.Request) {
	tmp := template.Must(template.ParseFiles("index.html"))
	if err := tmp.Execute(w, nil); err != nil {
		log.Fatal(err)
	}
}

func main() {
	http.HandleFunc("/upload", upload)
	http.HandleFunc("/", index)
	log.Fatal(http.ListenAndServe(":8000", nil))
}

index.html

index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>ファイルアップロード</title>
  </head>
  <body>
    <div class="container">
      <h1>ファイルアップロード</h1>
      <form method="post" action="/upload" enctype="multipart/form-data">
        <input type="file" name="image" multiple="multiple" />
        <input type="submit" name="submit" value="アップロード" />
      </form>
    </div>
  </body>
</html>

外観

スクリーンショット 2020-07-23 12.02.25.png ## できなかったこと テンプレートで \追記 githubに置いておきました。
3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?