codecamp

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 you'd 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))​:该语句拼接字符串用来当做存储文件的路径


iris Multipart/Urlencoded 表单
iris 路由组
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }