首先我们需要一个简单的上传文件网页,代码如下
<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" , iris.WithPostMaxMemory(maxSize))
}
app.RegisterView(iris.HTML("./templates", ".html"))
:该语句指定iris解析网页模板_, err = ctx.SaveFormFile(fh, filepath.Join("./uploads", fh.Filename))
:该语句拼接字符串用来当做存储文件的路径该模块由Tornado内部使用。不一定期望此处定义的函数和类对其他应用程序有用,但如果有用,它们会在此处记录。该模块的一个面向...
你可以使用与 Python 格式化字符串相同的语法来声明路径"参数"或"变量":from fastapi import FastAPIapp = FastAPI()@app.get("...
你可以在任意的路径操作中使用response_model参数来声明用于响应的模型:@app.get()@app.post()@app.put()@app.delete()等...
Web应用程序通常需要静态文件,例如javascript文件或支持网页显示的CSS文件。通常,配置Web服务器并为您提供这些服务,但在开发...