登录
首页 >  Golang >  Go教程

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

来源:脚本之家

时间:2023-02-16 15:37:30 440浏览 收藏

本篇文章向大家介绍《GO语言实现文件上传代码分享》,主要包括GO文件上传,具有一定的参考价值,需要的朋友可以参考一下。

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

代码如下:
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, "

我的第一个页面

")
    } 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语言有所帮助。

本篇关于《GO语言实现文件上传代码分享》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:脚本之家 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>
评论列表