• 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")
    }
  • 相关阅读:
    ajax提交表单,包括跳入的坑!
    js继承
    文本的选取和复制
    js 绑定的键盘事件
    webpack的使用 一、webpack 和webpack的安装
    json转化为C#、Java、TypeScript、VisualBasic、Python实体类
    ASP.NET MVC Route详解
    .net面试技术要点总结
    C#利用反射实现简单记事本功能插件
    ASP.NET网页请求以及处理全过程(反编译工具查看源代码)
  • 原文地址:https://www.cnblogs.com/shenjianping/p/16125095.html
Copyright © 2020-2023  润新知