iris 上传文件

首先我们需要一个简单的上传文件网页,代码如下

<html>

<head>
	<title>Upload file</title>
</head>

<body>
	<form enctype="multipart/form-data" action="http://127.0.0.1:8080/upload" method="POST">
		<input type="file" name="uploadfile" />
		<input type="hidden" name="token" value="{{.}}" />
		<input type="submit" value="upload" />
	</form>
</body>

</html>

在go语言中写入上传文件代码

package main

import (
	"crypto/md5"
	"fmt"
	"io"
	"path/filepath"
	"strconv"
	"time"

	"github.com/kataras/iris/v12"
)

const maxSize = 5 << 20 // 5MB

func main() {
	app := iris.New()

	app.RegisterView(iris.HTML("./templates", ".html"))

	// Serve the upload_form.html to the client.
	app.Get("/upload", func(ctx iris.Context) {
		// create a token (optionally).

		now := time.Now().Unix()
		h := md5.New()
		io.WriteString(h, strconv.FormatInt(now, 10))
		token := fmt.Sprintf("%x", h.Sum(nil))

		// render the form with the token for any use youd like.
		// ctx.ViewData("", token)
		// or add second argument to the `View` method.
		// Token will be passed as {{.}} in the template.
		ctx.View("upload_form.html", token)
	})

	
	// Handle the post request from the upload_form.html to the server
	app.Post("/upload", iris.LimitRequestBodySize(maxSize+1<<20), func(ctx iris.Context) {
		// Get the file from the request.
		f, fh, err := ctx.FormFile("uploadfile")
		if err != nil {
			ctx.StatusCode(iris.StatusInternalServerError)
			ctx.HTML("Error while uploading: <b>" + err.Error() + "</b>")
			return
		}
		defer f.Close()

		_, err = ctx.SaveFormFile(fh, filepath.Join("./uploads", fh.Filename))
		if err != nil {
			ctx.StatusCode(iris.StatusInternalServerError)
			ctx.HTML("Error while uploading: <b>" + err.Error() + "</b>")
			return
		}
	})

	// start the server at http://localhost:8080 with post limit at 5 MB.
	app.Listen(":8080" /* 0.*/, iris.WithPostMaxMemory(maxSize))
}
  • app.RegisterView(iris.HTML("./templates", ".html"))​:该语句指定iris解析网页模板
  • _, err = ctx.SaveFormFile(fh, filepath.Join("./uploads", fh.Filename))​:该语句拼接字符串用来当做存储文件的路径

作者:唐伯虎点蚊香,如若转载,请注明出处:https://www.web176.com/iris/21992.html

(0)
打赏 支付宝 支付宝 微信 微信
唐伯虎点蚊香的头像唐伯虎点蚊香
上一篇 2023年5月19日
下一篇 2023年5月19日

相关推荐

发表回复

登录后才能评论