Go语言Web : 上传文件

如何上传文件到指定目录

// upload-files.go
package main

import (
    "crypto/md5"
    "fmt"
    "io"
    "os"
    "strconv"
    "time"

    "gopkg.in/kataras/iris.v6"
    "gopkg.in/kataras/iris.v6/adaptors/httprouter"
    "gopkg.in/kataras/iris.v6/adaptors/view"
)

func main() {
    app := iris.New()
    app.Adapt(iris.DevLogger())
    app.Adapt(httprouter.New())
    app.Adapt(view.HTML("./templates", ".html"))

    // 提供form.html页面给用户
    app.Get("/upload", func(ctx *iris.Context) {
        //创建token (可选项)

        now := time.Now().Unix()
        h := md5.New()
        io.WriteString(h, strconv.FormatInt(now, 10))
        token := fmt.Sprintf("%x", h.Sum(nil))
        //轮打token
        ctx.Render("upload_form.html", token)
    })

    // 处理post上传请求
    app.Post("/upload", iris.LimitRequestBodySize(10<<20),
        func(ctx *iris.Context) {
            //或者使用ctx.SetMaxRequestBodySize(10 << 20)
            //来限制文件大小

            //获取文件
            file, info, err := ctx.FormFile("uploadfile")

            if err != nil {
                ctx.HTML(iris.StatusInternalServerError,
                    "Error while uploading: <b>"+err.Error()+"</b>")
                return
            }

            defer file.Close()
            fname := info.Filename

            // 不更改文件名
            //  'uploads'文件夹假设已经存在
            out, err := os.OpenFile("./uploads/"+fname,
                os.O_WRONLY|os.O_CREATE, 0666)

            if err != nil {
                ctx.HTML(iris.StatusInternalServerError,
                    "Error while uploading: <b>"+err.Error()+"</b>")
                return
            }
            defer out.Close()

            io.Copy(out, file)
        })

    //在127.0.0.1:8080启动服务
    app.Listen(":8080")
}
$ tree ./
templates/
└── upload_form.html
uploads/
└──
$ go run upload-files.go

results matching ""

    No results matching ""