2017年6月12日 星期一

Golang : (net/http) Upload File

使用原生 net/http 做上傳檔案路由。

HTML 渲染 (gtpl)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>File Upload</title>
</head>
<body>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="uploadfile" />
        <input type="submit" value="upload">
    </form>
</body>
</html>

File Upload (file_upload.go)
package main

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

)

func upload(w http.ResponseWriter, r *http.Request){
 r.ParseForm()
 if r.Method == "GET"{

  //add time-token
  crutime := time.Now().Unix()
  h := md5.New()
  io.WriteString(h, strconv.FormatInt(crutime,10))
  token := fmt.Sprintf("%x",h.Sum(nil))

  //render from file
  t, _ := template.ParseFiles("upload.gtpl")
  t.Execute(w, token);

 } else {

  //validate token
  r.ParseForm()
  token := r.Form.Get("token")
  if token != ""{
   
  }else{
   fmt.Fprintlnf()
   return
  }

  //parse multipart/form-data
  r.ParseMultipartForm( 32 << 20)

  //get file (body - form_name -> <input ... name="uploadfile" />)
  file, handler, err := r.FormFile("uploadfile") //body parser - name
  if err != nil{
   fmt.Println(err)
   return
  }
  defer file.Close()
  fmt.Fprintf(w, "%v", handler.Header)

  //create file to ./test/xxxxxxx.xxx
  f, err := os.OpenFile("./test/"+handler.Filename, os.O_WRONLY| os.O_CREATE, 0666)

  if err != nil {
   fmt.Println(err)
   return
  }
  defer f.Close()

  //write copy io to  ./test/xxxxxxx.xxx
  io.Copy(f, file)
 }
}

func main(){
    http.HandleFunc("/upload", upload)
    err := http.ListenAndServe(":9090",nil)
    if err != nil{
     log.Fatal("Error:",err)
    }
}
1

沒有留言:

張貼留言

© ERIC RILEY , 自由無須告知轉貼
Background Japanese Sayagata by Olga Libby