前端:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form action="路由" method="post" enctype="multipart/form-data">
图片:<br>
<input type="file" name="file" value="请上传图片">
<br><br>
<input type="submit" value="submit">
</form>
</body>
</html>
后端:不建议图片入库
func AAA(c *gin.Context) {
file, err := c.FormFile("file")
if err != nil {
c.String(http.StatusBadRequest, fmt.Sprintf("FormFile err : %s", err.Error()))
return
}
var path = file.Filename
ok := c.SaveUploadedFile(file, `./upload/`+path)
if ok != nil {
c.String(http.StatusBadRequest, fmt.Sprintf("c.SaveUploadedFile err : %s", err.Error()))
return
}
c.String(http.StatusOK, "lala")
open, err := os.Open(`./upload/` + path)
if err != nil {
c.String(http.StatusBadRequest, fmt.Sprintf("os.Open(`./upload/`+path) err : %s", err.Error()))
return
}
defer open.Close()
// FileInfo:
stats, err := open.Stat()
if err != nil {
c.String(http.StatusBadRequest, fmt.Sprintf("open.Stat() err : %s", err.Error()))
return
}
// []byte
data := make([]byte, stats.Size())
_, err = open.Read(data)
if err != nil {
c.String(http.StatusBadRequest, fmt.Sprintf(" open.Read(data) err : %s", err.Error()))
return
}
// 比较懒直接转码入库,应该数据库存个文件存放路径
imgStr := base64.StdEncoding.EncodeToString(data)
......