package main
import (
"github.com/gin-gonic/gin"
"github.com/satori/go.uuid"
"io"
"net/http"
"os"
"path"
)
const (
//最大上传 100M
SR_File_Max_Bytes = 1024 * 1024 * 100
//目录
saveDir = "/home/go-file/"
httpUrl = "http://***:8090"
httpDir = "/static"
)
func main() {
router := gin.Default()
//本地上传到服务器 csv格式,其他类似 读取内容
router.POST("/upload", uploadFile)
router.StaticFS(httpDir, http.Dir(saveDir))
// 默认启动的是 8080端口,也可以自己定义启动端口
router.Run(":8090")
}
func uploadFile(c *gin.Context) {
rFile, err := c.FormFile("file")
if err != nil {
c.JSON(
http.StatusOK, gin.H{
"rsCode": 999,
"body": nil,
"msg": "文件格式错误",
},
)
return
}
if rFile.Size > SR_File_Max_Bytes {
c.JSON(
http.StatusOK, gin.H{
"rsCode": 999,
"body": nil,
"msg": "文件大小超过100M",
},
)
return
}
file, err := rFile.Open()
if err != nil {
c.JSON(
http.StatusOK, gin.H{
"rsCode": 999,
"body": nil,
"msg": "文件格式错误",
},
)
return
}
// 生成文件名 uuid //获取文件名带后缀
fileName := uuid.NewV4().String() + path.Ext(rFile.Filename)
// 拼接保存路径
savePath := saveDir + fileName
//打开目录
localFileInfo, fileStatErr := os.Stat(saveDir)
//目录不存在
if fileStatErr != nil || !localFileInfo.IsDir() {
//创建目录
errByMkdirAllDir := os.MkdirAll(saveDir, 0755)
if errByMkdirAllDir != nil {
c.JSON(http.StatusOK, gin.H{
"rsCode": 999,
"body": saveDir,
"msg": "创建目录失败",
})
return
}
}
out, err := os.Create(savePath)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"rsCode": 999,
"body": saveDir,
"msg": "保存文件失败",
})
return
}
defer out.Close()
_, err = io.Copy(out, file)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"rsCode": 999,
"body": savePath,
"msg": err.Error(),
})
return
}
//没有错误的情况下
c.JSON(http.StatusOK, gin.H{
"rsCode": 0,
"body": httpUrl + httpDir + "/" + fileName,
"msg": "上传成功",
})
return
}
打包成可在linux运行的文件
$ set GOARCH=amd64
$ set GOOS=linux
开发完成,构建打包为一个名为go-file的文件
$ go build -o go-file main.go
上传go-file到服务器
加权限成可执行文件,输出日志到file.log,并置后台&
$ chmod 755 go-file
$ ./go-file > file.log &