GO语言实现文件上传代码分享
功能很简单,代码也很简洁,这里就不多废话了。
packagemain
import(
"fmt"
"io"
"net/http"
"os"
)
const(
upload_pathstring="./upload/"
)
funchelloHandle(whttp.ResponseWriter,r*http.Request){
io.WriteString(w,"helloworld!")
}
//上传
funcuploadHandle(whttp.ResponseWriter,r*http.Request){
//从请求当中判断方法
ifr.Method=="GET"{
io.WriteString(w,"<html><head><title>我的第一个页面</title></head><body><formaction=''method=\"post\"enctype=\"multipart/form-data\"><label>上传图片</label><inputtype=\"file\"name='file' /><br/><label><inputtype=\"submit\"value=\"上传图片\"/></label></form></body></html>")
}else{
//获取文件内容要这样获取
file,head,err:=r.FormFile("file")
iferr!=nil{
fmt.Println(err)
return
}
deferfile.Close()
//创建文件
fW,err:=os.Create(upload_path+head.Filename)
iferr!=nil{
fmt.Println("文件创建失败")
return
}
deferfW.Close()
_,err=io.Copy(fW,file)
iferr!=nil{
fmt.Println("文件保存失败")
return
}
//io.WriteString(w,head.Filename+"保存成功")
http.Redirect(w,r,"/hello",http.StatusFound)
//io.WriteString(w,head.Filename)
}
}
funcmain(){
//启动一个http服务器
http.HandleFunc("/hello",helloHandle)
//上传
http.HandleFunc("/image",uploadHandle)
err:=http.ListenAndServe(":8080",nil)
iferr!=nil{
fmt.Println("服务器启动失败")
return
}
fmt.Println("服务器启动成功")
}
以上所述就是本文的全部内容了,希望大家能够喜欢,能够对大家学习go语言有所帮助。