go语言开发时,遇到网站上传图片的问题,网上的资料很多不能用,最后自己测试通过一种方法。
1、router
package user
import (
"Project/auth"
"github.com/gorilla/mux"
)
// UserAPI
func UserAPI(r *mux.Router) {
privateRouter := r.PathPrefix("/user").Subrouter()
privateRouter.HandleFunc("/create", createOne).Methods("POST")
privateRouter.Use(auth.CheckAuth)
}
2、controller
package user
import (
"encoding/json"
"net/http"
"os"
"Project/utils"
"strconv"
"strings"
"time"
"github.com/gorilla/mux"
"github.com/gorilla/schema"
"io"
"path"
)
// 创建方法
func createOne(w http.ResponseWriter, r *http.Request) {
// 获得图片对象
uploadFile, handle, err := r.FormFile("img")
if err != nil {
utils.RespondWithError(w, 500, "img err")
return
}
// 验证后缀名
ext := strings.ToLower(path.Ext(handle.Filename))
if ext != ".jpg" && ext != ".png" {
utils.RespondWithError(w, 500, "img err-2")
return
}
// 拼接图片url
currentTime := time.Now().Format("20060102150405")
//上边字符串为golang诞生时间,时间转字符串要按照这个格式来整
imgName := currentTime + ext
uploadPATH = "static/img/" + imgName
// 保存图片并结束
saveFile, err := os.OpenFile(uploadPATH , os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
utils.RespondWithError(w, 500, "img err")
return
}
io.Copy(saveFile, uploadFile)
defer uploadFile.Close()
defer saveFile.Close()
return
}