Fork me on GitHub

Gin框架系列之文件上传

一、Form表单上传

(一)单文件上传

  • 前端
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/post_upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="提交">
</form>
</body>
</html>
  • 后端
package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "net/http"
)

func GetUpload(ctx *gin.Context) {
    ctx.HTML(http.StatusOK, "index.html", nil)
}

func PostUpload(ctx *gin.Context) {
    file, _ := ctx.FormFile("file")
    file_path := "./upload/" + file.Filename // 设置文件路径
    fmt.Println(file_path)
    _ = ctx.SaveUploadedFile(file, file_path) // 保存文件
    ctx.String(http.StatusOK, "上传成功")

}

func main() {
    router := gin.Default()
    // 加载模板文件
    router.LoadHTMLGlob("template/*")

    router.GET("/get_upload", GetUpload)
    router.POST("/post_upload", PostUpload)

    router.Run(":8080")
}

(二)多文件上传

  • 前端
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/post_upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file"><br>
    <input type="file" name="file"><br>
    <input type="submit" value="提交">
</form>
</body>
</html>
  • 后端
package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
    "strconv"
    "time"
)

func GetUpload(ctx *gin.Context) {
    ctx.HTML(http.StatusOK, "index.html", nil)
}

func PostUpload(ctx *gin.Context) {
    form, _ := ctx.MultipartForm()
    files := form.File["file"]

    for _, file := range files {
        unix_time := time.Now().Unix() // int类型的时间戳
        unix_time_str := strconv.FormatInt(unix_time, 10)
        file_path := "./upload/" + unix_time_str + file.Filename
        ctx.SaveUploadedFile(file, file_path)
    }
    ctx.String(http.StatusOK, "上传成功")

}

func main() {
    router := gin.Default()

    router.LoadHTMLGlob("template/*")

    router.GET("/get_upload", GetUpload)
    router.POST("/post_upload", PostUpload)

    router.Run(":8080")
}

二、Ajax上传

(一)单文件上传

  • 前端
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/static/js/jquery-3.6.0.js"></script>
</head>
<body>
<form>
    <input type="file" id="file">
    <input type="button" value="提交" id="btn_submit">
</form>
<script>
    var btn_submit = document.getElementById("btn_submit")
    btn_submit.onclick = function (ev) {
        var file = $("#file")[0].files[0];
        var form_data = new FormData();
        form_data.append("file", file);
        
        $.ajax({
            url: "/post_upload",
            type: "POST",
            data: form_data,
            contentType: false,
            processData: false,
            success: function (data) {
                // 响应回来的json数据
            },
            fail: function (data) {
                
            }
            
        })
    }
    
    
</script>
</body>
</html>
  • 后端
package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "net/http"
)

func GetUpload(ctx *gin.Context)  {
    ctx.HTML(http.StatusOK, "index.html", nil)
}

func PostUpload(ctx *gin.Context) {
    file, _ := ctx.FormFile("file")
    file_path := "./upload/" + file.Filename // 设置文件路径
    fmt.Println(file_path)
    _ = ctx.SaveUploadedFile(file, file_path) // 保存文件
    ctx.String(http.StatusOK, "上传成功")

}

func main()  {
    router := gin.Default()

    router.LoadHTMLGlob("template/*")
    router.Static("/static", "static")

    router.GET("/get_upload", GetUpload)
    router.POST("/post_upload", PostUpload)


    router.Run(":8080")
}

(二)多文件上传

  • 前端
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/static/js/jquery-3.6.0.js"></script>
</head>
<body>
<form>
    <input type="file" class="file">
    <input type="file" class="file">
    <input type="button" value="提交" id="btn_submit">
</form>
<script>
    var btn_submit = document.getElementById("btn_submit")
    btn_submit.onclick = function (ev) {
        var files = $(".file")
        var form_data = new FormData();


        for (var i = 0; i < files.length; i++) {
            var file = files[i].files[0];
            form_data.append("file", file);
        }

        $.ajax({
            url: "/post_upload",
            type: "POST",
            data: form_data,
            contentType: false,
            processData: false,
            success: function (data) {
                // 响应回来的json数据
            },
            fail: function (data) {

            }

        })
    }


</script>
</body>
</html>
  • 后端
package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
    "strconv"
    "time"
)

func GetUpload(ctx *gin.Context) {
    ctx.HTML(http.StatusOK, "index.html", nil)
}

func PostUpload(ctx *gin.Context) {
    form, _ := ctx.MultipartForm()
    files := form.File["file"]

    for _, file := range files {
        unix_time := time.Now().Unix() // int类型的时间戳
        unix_time_str := strconv.FormatInt(unix_time, 10)
        file_path := "./upload/" + unix_time_str + file.Filename
        ctx.SaveUploadedFile(file, file_path)
    }
    ctx.String(http.StatusOK, "上传成功")

}

func main() {
    router := gin.Default()

    router.LoadHTMLGlob("template/*")

    router.GET("/get_upload", GetUpload)
    router.POST("/post_upload", PostUpload)

    router.Run(":8080")
}

 

posted @ 2022-04-10 19:36  iveBoy  阅读(685)  评论(0编辑  收藏  举报
TOP