You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

306 lines
8.8 KiB
Go

5 months ago
package controllers
import (
"bufio"
"crypto/md5"
"fmt"
"goftp/service"
"goftp/utils"
"io"
"math/rand"
"net/http"
"os"
"path"
"path/filepath"
"time"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
)
type FileOptUploadController struct {
beego.Controller
}
// @Title Get
// @Description 上传文件
// @router / [get]
func (c *FileOptUploadController) Get() {
c.TplName = "fileopt.html"
}
// @Title FileUploadPost
// @Description 上传文件
// @router /fileUploadPost [post]
func (c *FileOptUploadController) FileUploadPost() {
f, h, _ := c.GetFile("file") //获取上传的文件
ext := path.Ext(h.Filename)
//创建目录
goftpdir := beego.AppConfig.String("macgoftpdir")
servergoftpdir := beego.AppConfig.String("servergoftpdir")
if utils.ValiteDirExist(servergoftpdir) == true {
goftpdir = servergoftpdir
}
uploadDir := utils.CreateBaseDir(goftpdir)
//uploadDir := utils.CreateBaseDir("/Users/edao/goftpdir");
//uploadDir := "/root/goftpdir"
//构造文件名称
rand.Seed(time.Now().UnixNano())
randNum := fmt.Sprintf("%d", rand.Intn(9999)+1000)
hashName := md5.Sum([]byte(time.Now().Format("2006_01_02_15_04_05_") + randNum))
fileName := fmt.Sprintf("%x", hashName) + ext
fpath := uploadDir + "/" + fileName
defer f.Close()
//写文件保存excel文件
r := bufio.NewReader(f) //创建一个读取缓冲流
fo, err := os.Create(fpath) //创建输出*File
if err != nil {
logs.Error(err)
}
w := bufio.NewWriter(fo) //创建输出缓冲流
buf := make([]byte, 1024)
for {
n, err := r.Read(buf)
if err != nil && err != io.EOF {
logs.Error(err)
}
if n == 0 {
break
}
if n2, err := w.Write(buf[:n]); err != nil {
logs.Error(err)
} else if n2 != n {
logs.Debug("error in writing")
}
}
if err = w.Flush(); err != nil {
logs.Error(err)
}
webUrl := beego.AppConfig.String("webUrl")
if utils.ValiteDirExist(servergoftpdir) == false {
webUrl = "http://127.0.0.1:5000"
}
c.Ctx.WriteString("上传成功~,文件URL:" + webUrl + "/goftp/file/getSingleFile?fileName=" + fileName)
}
// @Title PicUploadPost
// @Description 上传图片
// @router /picUploadPost [post]
func (c *FileOptUploadController) PicUploadPost() {
f, h, err := c.GetFile("file") //获取上传的文件
if err != nil {
c.Ctx.WriteString("请选择上传的图片")
return
}
ext := path.Ext(h.Filename)
//验证后缀名是否符合要求
var AllowExtMap map[string]bool = map[string]bool{
".jpg": true,
".jpeg": true,
".png": true,
}
if _, ok := AllowExtMap[ext]; !ok {
c.Ctx.WriteString("后缀名不符合上传要求")
return
}
//创建目录
//uploadDir := "static/upload/" + time.Now().Format("2006/01/02/")
servergoftpdir := beego.AppConfig.String("servergoftpdir")
uploadDir := utils.CreateDir("static", "pic")
uploadPath := "static" + "/" + "pic"
//构造文件名称
rand.Seed(time.Now().UnixNano())
randNum := fmt.Sprintf("%d", rand.Intn(9999)+1000)
hashName := md5.Sum([]byte(time.Now().Format("2006_01_02_15_04_05_") + randNum))
fileName := fmt.Sprintf("%x", hashName) + ext
fpath := uploadDir + "/" + fileName
defer f.Close()
//写文件保存excel文件
r := bufio.NewReader(f) //创建一个读取缓冲流
fo, err := os.Create(fpath) //创建输出*File
if err != nil {
logs.Error(err)
}
w := bufio.NewWriter(fo) //创建输出缓冲流
buf := make([]byte, 1024)
for {
n, err := r.Read(buf)
if err != nil && err != io.EOF {
logs.Error(err)
}
if n == 0 {
break
}
if n2, err := w.Write(buf[:n]); err != nil {
logs.Error(err)
} else if n2 != n {
logs.Debug("error in writing")
}
}
if err = w.Flush(); err != nil {
logs.Error(err)
}
//webUrl
webUrl := beego.AppConfig.String("webUrl")
if utils.ValiteDirExist(servergoftpdir) == false {
webUrl = "http://127.0.0.1:5000"
}
c.Ctx.WriteString("上传成功~,文件路径为:" + webUrl + "/goftp/" + uploadPath + "/" + fileName)
}
// @Title GetSingleFile
// @Description 获取单个文件
// @Param fileName query string true "文件名称"
// @router /getSingleFile [get]
func (c *FileOptUploadController) GetSingleFile() {
//图片,text,pdf文件全部在浏览器中显示了并没有完全的实现下载的功能
fileName := c.Ctx.Input.Query("fileName")
logs.Debug(fileName)
goftpdir := beego.AppConfig.String("macgoftpdir")
servergoftpdir := beego.AppConfig.String("servergoftpdir")
if utils.ValiteDirExist(servergoftpdir) == true {
goftpdir = servergoftpdir
}
logs.Debug(fileName)
if fileName == "" {
c.Ctx.WriteString("please input you want to download the file name!")
return
}
filePath := goftpdir + "/" + fileName
if utils.ValiteFileExist(filePath) == false {
c.Ctx.WriteString("file not exist!")
return
}
fileCountUpdateSuccess := service.UpdateDownloadCount(fileName)
if fileCountUpdateSuccess {
logs.Debug("fileCountUpdatesuccess")
} else {
logs.Debug("fileCountUpdateFail")
}
c.Download(filePath, fileName)
}
// @Title GetEx4File
// @Description 获取单个文件
// @Param fileName query string true "文件名称"
// @router /getEx4File [get]
func (c *FileOptUploadController) GetEx4File() {
//图片,text,pdf文件全部在浏览器中显示了并没有完全的实现下载的功能
fileName := c.Ctx.Input.Query("fileName")
logs.Debug(fileName)
goftpdir := beego.AppConfig.String("macgoftpdir")
servergoftpdir := beego.AppConfig.String("servergoftpdir")
if utils.ValiteDirExist(servergoftpdir) == true {
goftpdir = servergoftpdir
}
logs.Debug(fileName)
if fileName == "" {
c.Ctx.WriteString("please input you want to download the file name!")
return
}
filePath := goftpdir + "/" + fileName
if utils.ValiteFileExist(filePath) == false {
c.Ctx.WriteString("file not exist!")
return
}
fileCountUpdateSuccess := service.UpdateDownloadCount(fileName)
if fileCountUpdateSuccess {
logs.Debug("fileCountUpdatesuccess")
} else {
logs.Debug("fileCountUpdateFail")
}
c.Download(filePath, fileName)
}
// @Title UploadBaseFilePost
// @Description 上传原文件,文件名称不会改变
// @router /uploadBaseFileToGoFtpDir [post]
func (c *FileOptUploadController) UploadBaseFileToPost() {
f, h, _ := c.GetFile("file") //获取上传的文件
//ext := path.Ext(h.Filename)
logs.Debug(h.Filename)
//创建目录
goftpdir := beego.AppConfig.String("macgoftpdir")
servergoftpdir := beego.AppConfig.String("servergoftpdir")
if utils.ValiteDirExist(servergoftpdir) == true {
goftpdir = servergoftpdir
}
uploadDir := utils.CreateBaseDir(goftpdir)
//uploadDir := utils.CreateBaseDir("/Users/edao/goftpdir");
//uploadDir := "/root/goftpdir"
//构造文件名称
// rand.Seed(time.Now().UnixNano())
// randNum := fmt.Sprintf("%d", rand.Intn(9999)+1000)
// hashName := md5.Sum([]byte(time.Now().Format("2006_01_02_15_04_05_") + randNum))
fileName := h.Filename
fpath := uploadDir + "/" + fileName
defer f.Close()
//写文件保存excel文件
r := bufio.NewReader(f) //创建一个读取缓冲流
fo, err := os.Create(fpath) //创建输出*File
if err != nil {
logs.Error(err)
}
w := bufio.NewWriter(fo) //创建输出缓冲流
buf := make([]byte, 1024)
for {
n, err := r.Read(buf)
if err != nil && err != io.EOF {
logs.Error(err)
}
if n == 0 {
break
}
if n2, err := w.Write(buf[:n]); err != nil {
logs.Error(err)
} else if n2 != n {
logs.Debug("error in writing")
}
}
if err = w.Flush(); err != nil {
logs.Error(err)
}
webUrl := beego.AppConfig.String("webUrl")
if utils.ValiteDirExist(servergoftpdir) == false {
webUrl = "http://127.0.0.1:5000"
}
//c.Ctx.WriteString("上传成功~,服务器文件路径为:" + fpath)
//c.Ctx.WriteString("\n")
//c.Ctx.ResponseWriter.AddHeader("content-disposition", "attachment; filename=\""+fileName+"\"")
c.Ctx.WriteString("上传成功~,文件URL:" + webUrl + "/goftp/file/getSingleFile?fileName=" + fileName)
}
// 重写beego框架 Download 方法去掉文件名url.QueryEscape(fName)
func (c *FileOptUploadController) Download(file string, filename ...string) {
// check get file error, file not found or other error.
if _, err := os.Stat(file); err != nil {
http.ServeFile(c.Ctx.Output.Context.ResponseWriter, c.Ctx.Output.Context.Request, file)
return
}
var fName string
if len(filename) > 0 && filename[0] != "" {
fName = filename[0]
} else {
fName = filepath.Base(file)
}
c.Ctx.Output.Header("Content-Disposition", "attachment; filename="+fName)
c.Ctx.Output.Header("Content-Description", "File Transfer")
c.Ctx.Output.Header("Content-Type", "application/octet-stream")
c.Ctx.Output.Header("Content-Transfer-Encoding", "binary")
c.Ctx.Output.Header("Expires", "0")
c.Ctx.Output.Header("Cache-Control", "must-revalidate")
c.Ctx.Output.Header("Pragma", "public")
http.ServeFile(c.Ctx.Output.Context.ResponseWriter, c.Ctx.Output.Context.Request, file)
}