0
0

More than 3 years have passed since last update.

Golangでwebアップローダーを作る

Last updated at Posted at 2020-03-15

とりあえず作成したので、アップロード
https://github.com/karosuwindam/goupload

重要部分を抜き出し
アップロードの関数部分

upload.go
package main
import (
    "fmt"
    "net/http"
    "os"

)

const UPLOAD = "upload"

func upload(w http.ResponseWriter, r *http.Request) {
    var data []byte = make([]byte, 1024)
    var tmplength int64 = 0
    var output string
    urldata := ""
    searchdata := ""
    if r.Method == "POST" {
        file, fileHeader, e := r.FormFile("file")
        if e != nil {
            fmt.Fprintf(w, "アップロードに失敗しました。")
            return
        }
        writefilename := fileHeader.Filename
        fp, err := os.Create(UPLOAD + "/" + writefilename)
        if err != nil {
        }
        defer fp.Close()
        defer file.Close()
        for {
            n, e := file.Read(data)
            if n == 0 {
                break
            }
            if e != nil {
                return
            }
            fp.WriteAt(data, tmplength)
            tmplength += int64(n)
        }
        fmt.Printf("POST\n")
    } else {
        fmt.Printf("GET\n")
                fmt.Fprintf(w, "GET読み込み")
        return
    }
    fmt.Fprintf(w, "ファイルアップロード")
}

サーバのスタート部分

main.go
package main

import (
    "net/http"
    "fmt"
)

const Port = "8080"
const Ipdata = ""


func webstart() {
    http.HandleFunc("/upload/", upload)
    http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("./html"))))
    http.ListenAndServe(Ipdata+":"+Port, nil)
}

func main() {
    fmt.Printf("%v:%v Webserver start\n", Ipdata, Port)
    webstart()
}

index部分ファイルアップロードはブラウザのPOST命令に任せる

index.html
<html>
    <head>
        <title>upload</title>
    </head>
    <body>
        <form action="/upload/" method="post" enctype="multipart/form-data">
        <input type="file" name="file" id="up_loadfile" multiple="multiple">
        <input type="submit" value="send">
        </form>
    </body>
</html>

メモ書き程度なので、githubのアップロードファイルをビルドした方が多機能かも

0
0
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
0
0