package main
import (
"fmt"
"io"
"net/
http"
"os"
)
const (
upload_path
String = "./upload/"
)
func
HelloHandle(w
http.ResponseWriter,r *
http.
request)
{
io.Write
String(w,"
Hello World!")
}
//
上传
func uploadHandle(w
http.ResponseWriter,r *
http.
request)
{
//从请求当中判断
方法
if r.Method == "GET"
{
io.Write
String(w,"<html><head><
title>我的第
一个页面</
title></head><body><form action='' method=\"post\" enctype=\"multipart/form-data\"><label>
上传图片</label><input type=\"file\" name='file' /><br/><label><input type=\"submit\" value=\"
上传图片\"/></label></form></body></html>")
} else
{
//
获取文件内容 要这样
获取
file,head,err := r.FormFile("file")
if err
!= nil
{
fmt.Println(err)
return
}
defer file.Close()
//
创建文件
fW,err := o
s.Create(upload_path + head.File
Name)
if err
!= nil
{
fmt.Println("
文件创建失败")
return
}
defer fW.Close()
_,err = io.Copy(fW,fil
E)
if err
!= nil
{
fmt.Println("
文件保存失败")
return
}
//io.Write
String(w,head.Fil
ename+" 保存成功")
http.Redirect(w,r,"/
Hello",
http.StatusFound)
//io.Write
String(w,head.File
Name)
}
}
func main()
{
//启动
一个http 服务器
http.HandleFunc("/
Hello",
HelloHandl
E)
//
上传
http.HandleFunc("/image",uploadHandl
E)
err :=
http.ListenAndServe(":8080",nil)
if err
!= nil
{
fmt.Println("服务器启动失败")
return
}
fmt.Println("服务器启动成功")
}