golang 图片上传HTTP服务

windows或者ubuntu 都可以运行,post body 参数为:image ,上传图片格式为base64,新建一个static文件夹,图片存储在static文件夹中
 
package main

import (
    "fmt"
    "net/http"
    "log"
    "io/ioutil"
    "time"
    "encoding/base64"
)
func recieveImage(w http.ResponseWriter , r *http.Request){
    r.ParseForm()
    fmt.Println("path",r.URL.Path)
    imagebuff := r.Form["image"]
    formatTimeStr:=time.Now().Format("2006-01-02-15-04-05")
    fmt.Println(formatTimeStr)   //打印结果:2017-04-11 13:30:39 
    dataTimeString := "static/"+string(formatTimeStr)+".png"
    fmt.Println(dataTimeString)
    imageString := string(imagebuff[0])
   
    base2Img(imageString,dataTimeString)
    fmt.Fprintf(w,"submit sucess!")
}
func base2Img(imageString string,filename string){
    ddd, _ := base64.StdEncoding.DecodeString(imageString) 
    err :=ioutil.WriteFile(filename, ddd, 0666) 
    fmt.Println(err)
}
func welcomeUse(w http.ResponseWriter , r *http.Request){
    r.ParseForm()
    fmt.Println("path",r.URL.Path)
    fmt.Fprintf(w,"http server!")
}
func main(){
    fmt.Println("   welcome to use  http server  ")
    fmt.Println(" ")
    http.HandleFunc("/",welcomeUse)
    http.HandleFunc("/image/upload",recieveImage)
    err := http.ListenAndServe(":8080",nil)
    if err != nil{
        log.Fatal("ListenAndServe:",err)
    }
}
后知后觉、越学越菜
原文地址:https://www.cnblogs.com/chenhuanting/p/11678826.html