文件上传

单文件上传

  • 后端代码

    • 使用 FormFile(key) 接收前端传的参数
    • 使用SaveUploadFile(句柄,目标地址)
    // 生成文件名称
    func generate_filename() string{
    	return strconv.FormatInt(time.Now().Unix(),10)
    }
    
    // 获取文件的后缀名
    func file_ext(filename string) string  {
    	pos := strings.LastIndex(filename,".")
    	return filename[pos:]
    }
    
    // 确认上传
    func DoUpload(ctx *gin.Context){
    	file,_ := ctx.FormFile("pic")
    	ext := file_ext(file.Filename)
    	dist := "upload/" + generate_filename() + ext
    	ctx.SaveUploadedFile(file,dist)
    	ctx.String(http.StatusOK,"上传成功")
    }
    
  • 前端代码

    {{define "user/upload.html"}}
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>上传文件</title>
    </head>
    <body>
    <form action="/v4/upload" method="post" enctype="multipart/form-data">
        上传图片<input type="file" name="pic" /> <br>
        <input type="submit" value="提交"/>
    </form>
    </body>
    </html>
    {{end}}
    
  • 路由代码

    v4 := router.Group("/v4")
    {
        v4.POST("/upload",chapter4.DoUpload)
    }
    

多文件上传

  • 后端代码

    // 生成文件名称(时间戳)
    func generate_filename() string{
    	return strconv.FormatInt(time.Now().Unix(),10) + strconv.Itoa(rand.Intn(100000))
    }
    
    // 获取文件的后缀名
    func file_ext(filename string) string  {
    	pos := strings.LastIndex(filename,".")
    	return filename[pos:]
    }
    
    // 文件上传
    func UploadMoreView(ctx *gin.Context){
    	ctx.HTML(http.StatusOK,"upload/add.html",nil)
    }
    
    // 多文件上传
    func Moreupload(ctx *gin.Context)  {
        // 获取多文件的句柄
    	form,_ := ctx.MultipartForm()
        // 获取文件
    	files := form.File["pic"]
    	// 循环写入
    	for _,file := range files{
    		ext := file_ext(file.Filename)
    		filename := generate_filename()
    		fmt.Println(file.Filename)
    		ctx.SaveUploadedFile(file,"upload/"+filename+ext)
    	}
    
    	ctx.String(http.StatusOK,"上传成功")
    
    }
    
  • 前段代码

    {{define "upload/add.html"}}
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>多文件上传案例</title>
    </head>
    <body>
    <form action="/v5/upload" method="post" enctype="multipart/form-data">
        上传图片:<input type="file" name="pic" multiple />
        <input type="submit" value="提交"/>
    </form>
    </body>
    </html>
    {{end}}
    
  • 路由代码

    v5 := router.Group("/v5")
    {
    	v5.GET("/add",chapter4.UploadMoreView)
    	v5.POST("/upload",chapter4.Moreupload)
    }
    
原文地址:https://www.cnblogs.com/wuxiaoshi/p/14350717.html