background/controller/file.go

80 lines
1.5 KiB
Go
Raw Normal View History

2019-03-07 06:06:29 +00:00
package controller
2019-01-29 13:57:53 +00:00
import (
"github.com/gin-gonic/gin"
uuid "github.com/satori/go.uuid"
"io/ioutil"
2019-01-29 13:57:53 +00:00
"log"
"net/http"
2019-01-29 13:57:53 +00:00
"os"
"strings"
2019-01-29 13:57:53 +00:00
)
2019-03-07 06:06:29 +00:00
type FileController struct {
}
func (this *FileController) OnUpload(c *gin.Context) {
uid,e := uuid.NewV1()
if nil != e{
log.Print(e.Error())
return
2019-01-29 13:57:53 +00:00
}
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("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()})
2019-01-29 13:57:53 +00:00
}
}
2019-03-12 06:01:25 +00:00
func (this *FileController) OnDownLoad(c *gin.Context) {
2019-09-02 16:22:39 +00:00
resp := RespBase{Msg:"FAIL",Status: 211}
2019-09-02 16:22:39 +00:00
fileName := c.Param("file")
if "" == fileName{
c.JSON(200,resp)
2019-09-02 16:22:39 +00:00
return
}
file,e := os.Open("/home/ubuntu/api/bin/image/" +fileName + ".jpg")
2019-09-02 16:22:39 +00:00
if nil != e{
log.Print(e.Error())
c.JSON(200,resp)
2019-09-02 16:22:39 +00:00
return
2019-01-29 13:57:53 +00:00
}
2019-09-02 16:22:39 +00:00
bytes,e :=ioutil.ReadAll(file)
if nil != e{
log.Print(e.Error())
c.JSON(200,resp)
2019-09-02 16:22:39 +00:00
return
2019-01-29 13:57:53 +00:00
}
c.Header("X-Content-Type-Options", "nosniff")
2019-09-02 16:22:39 +00:00
c.Header("Content-Type","image/png")
c.Header("Content-Disposition",
"/image/" +fileName)
2019-09-02 16:22:39 +00:00
c.Writer.Write(bytes)
2019-01-29 13:57:53 +00:00
}