GO语言实现文件上传代码分享

(编辑:jimmy 日期: 2024/9/19 浏览:2)

功能很简单,代码也很简洁,这里就不多废话了。

复制代码 代码如下:
package main
import (
    "fmt"
    "io"
    "net/http"
    "os"
)
const (
    upload_path string = "./upload/"
)
func helloHandle(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "hello world!")
}
//上传
func uploadHandle(w http.ResponseWriter, r *http.Request) {
    //从请求当中判断方法
    if r.Method == "GET" {
        io.WriteString(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 := os.Create(upload_path + head.Filename)
        if err != nil {
            fmt.Println("文件创建失败")
            return
        }
        defer fW.Close()
        _, err = io.Copy(fW, file)
        if err != nil {
            fmt.Println("文件保存失败")
            return
        }
        //io.WriteString(w, head.Filename+" 保存成功")
        http.Redirect(w, r, "/hello", http.StatusFound)
        //io.WriteString(w, head.Filename)
    }
}
func main() {
    //启动一个http 服务器
    http.HandleFunc("/hello", helloHandle)
    //上传
    http.HandleFunc("/image", uploadHandle)
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        fmt.Println("服务器启动失败")
        return
    }
    fmt.Println("服务器启动成功")
}

以上所述就是本文的全部内容了,希望大家能够喜欢,能够对大家学习go语言有所帮助。

一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。