如何用form表单同时传图片和文本?------以go为例

322 篇文章 11 订阅
133 篇文章 57 订阅

       form表单很简单,我们也用过form表单来上传图片,会用到enctype="multipart/form-data", 而普通的文本, 又不需要这样。 那么, 当form表单中既有图片,又有文本, 该如何处理呢? 这种情况很常见啊!

        我想当然地写出如下代码:

        s.go为:

package main

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

func upload(c *gin.Context) {

    name := c.Query("username")
    log.Println("name is", name)


    file, header, err := c.Request.FormFile("file") 
    if err != nil {
        c.String(http.StatusBadRequest, fmt.Sprintf("file err : %s", err.Error()))
        return
    }

    filename := header.Filename
    out, err := os.Create("public/" + filename)
    if err != nil {
        log.Fatal(err)
    }
    defer out.Close()

    _, err = io.Copy(out, file)
    if err != nil {
        log.Fatal(err)
    }

    filepath := "http://localhost:8080/file/" + filename
    c.JSON(http.StatusOK, gin.H{"filepath": filepath})
}

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

    router.LoadHTMLGlob("template/*")
    router.GET("/", func(c *gin.Context) {
        c.HTML(http.StatusOK, "select_file.html", gin.H{})
    })

    router.POST("/upload", upload)
    
    router.StaticFS("/file", http.Dir("public"))
    router.Run(":8080")
}

        select_file.html为:

<html>
<body>
    <form action="http://localhost:8080/upload/" enctype="multipart/form-data" method="POST"> 
        <input type="file" name="file" id="pic" accept="*" /> <br />
        <input type="text" name="username" value="xxx">
        <button type="submit">提交</button>
    </form>
</body>
</html>

        我期望log.Println("name is", name)能打印出xxx,  可是, 没有。

        我很快就感觉到, 是因为图片和文本一起传递所致, 在网上搜了很多地方, 发现不少人也有这个疑问, 很多解答要么太复杂, 要么扯淡。请教了一位朋友, 让我尝试PostForm,  顺便查了一下官网, 试验了一下, 搞定, 问题解决。

        解决办法:把Query改为PostForm

 

 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值