background/controller/file.go

75 lines
1.4 KiB
Go

package controller
import (
"github.com/gin-gonic/gin"
uuid "github.com/satori/go.uuid"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
)
type FileController struct {
}
func (this *FileController) OnUpload(c *gin.Context) {
uid,e := uuid.NewV1()
if nil != e{
log.Print(e.Error())
return
}
file, _, err := c.Request.FormFile("image")
if nil != err || nil == file{
log.Print(err.Error())
return
}
bytes,err := ioutil.ReadAll(file)
if nil != err{
log.Print(err.Error())
return
}
header := make([]byte,512)
copy(header,bytes)
types := http.DetectContentType(header)
log.Print(types)
// jpg
if strings.Contains(types,"jpeg"){
defer file.Close()
out, err := os.Create("G://image//" + uid.String() + ".jpg")
if err != nil {
log.Fatal(err)
}
defer out.Close()
out.Write(bytes)
log.Print(len(bytes))
c.JSON(200, map[string] interface{}{"url":uid.String()})
}
}
func (this *FileController) OnDownLoad(c *gin.Context) {
resp := RespBase{Msg:"FAIL",Status: 211}
defer func() {
c.JSON(200,resp)
}()
fileName := c.Param("file")
if "" == fileName{
return
}
file,e := os.Open("G://image//" +fileName)
if nil != e{
log.Print(e.Error())
return
}
bytes,e :=ioutil.ReadAll(file)
if nil != e{
log.Print(e.Error())
return
}
c.Header("Content-Type","image/png")
c.Header("Content-Disposition",
"G://image//" +fileName)
c.Writer.Write(bytes)
}