Add new feature of image cache.

This commit is contained in:
zicla
2018-11-22 23:18:36 +08:00
parent 459fa036be
commit 6c19a3d321
5 changed files with 123 additions and 74 deletions

View File

@ -3,10 +3,11 @@ package rest
import ( import (
"fmt" "fmt"
"net/http" "net/http"
"os"
"regexp" "regexp"
"strconv" "strconv"
"time"
"strings" "strings"
"time"
) )
type AlienController struct { type AlienController struct {
@ -435,17 +436,48 @@ func (this *AlienController) Download(writer http.ResponseWriter, request *http.
} }
} }
//缓存
var uri string = request.RequestURI
//this.imageCacheDao.FindByUri(uri)
fmt.Printf(uri)
//对图片做缩放处理。 //对图片做缩放处理。
imageProcess := request.FormValue("imageProcess") imageProcess := request.FormValue("imageProcess")
if imageProcess == "resize" { if imageProcess == "resize" {
this.matterService.ResizeImage(writer, request, matter)
//如果是图片,那么能用缓存就用缓存
uri := request.RequestURI
imageCache := this.imageCacheDao.FindByUri(uri)
if imageCache != nil {
//直接使用缓存中的信息
this.matterService.DownloadFile(writer, request, CONFIG.MatterPath+imageCache.Path, matter.Name)
} else { } else {
this.matterService.DownloadFile(writer, request, matter)
//resize图片
dstImage := this.matterService.ResizeImage(request, CONFIG.MatterPath+matter.Path)
user := this.userDao.FindByUuid(matter.UserUuid)
//获取文件应该存放在的物理路径的绝对路径和相对路径。
absolutePath, relativePath := GetUserFilePath(user.Username, true)
absolutePath = absolutePath + "/" + filename
relativePath = relativePath + "/" + filename
fileWriter, err := os.Create(absolutePath)
this.PanicError(err)
defer fileWriter.Close()
//生成的图片输出到两个writer中去
this.matterService.DownloadImage(writer, fileWriter, dstImage, matter.Name)
//相关信息写到缓存中去
imageCache = &ImageCache{
UserUuid: matter.UserUuid,
MatterUuid: matter.Uuid,
Uri: uri,
Path: relativePath,
}
this.imageCacheDao.Create(imageCache)
}
} else {
this.matterService.DownloadFile(writer, request, CONFIG.MatterPath+matter.Path, matter.Name)
} }
} }

View File

@ -24,3 +24,4 @@ func (this *ImageCacheService) Detail(uuid string) *ImageCache {
return imageCache return imageCache
} }

View File

@ -25,7 +25,7 @@ func InstallDatabase() {
hasTable = db.HasTable(downloadToken) hasTable = db.HasTable(downloadToken)
if !hasTable { if !hasTable {
createDownloadToken := "CREATE TABLE `tank10_download_token` (`uuid` char(36) NOT NULL,`user_uuid` char(36) DEFAULT NULL COMMENT '用户uuid',`matter_uuid` char(36) DEFAULT NULL COMMENT '文件标识',`expire_time` timestamp NULL DEFAULT NULL COMMENT '授权访问的次数',`ip` varchar(45) DEFAULT NULL COMMENT '消费者的ip',`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='下载的token表';" createDownloadToken := "CREATE TABLE `tank20_download_token` (`uuid` char(36) NOT NULL,`user_uuid` char(36) DEFAULT NULL COMMENT '用户uuid',`matter_uuid` char(36) DEFAULT NULL COMMENT '文件标识',`expire_time` timestamp NULL DEFAULT NULL COMMENT '授权访问的次数',`ip` varchar(45) DEFAULT NULL COMMENT '消费者的ip',`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='下载的token表';"
db = db.Exec(createDownloadToken) db = db.Exec(createDownloadToken)
if db.Error != nil { if db.Error != nil {
LogPanic(db.Error) LogPanic(db.Error)
@ -37,7 +37,7 @@ func InstallDatabase() {
matter := &Matter{} matter := &Matter{}
hasTable = db.HasTable(matter) hasTable = db.HasTable(matter)
if !hasTable { if !hasTable {
createMatter := "CREATE TABLE `tank10_matter` (`uuid` char(36) NOT NULL,`puuid` varchar(45) DEFAULT NULL COMMENT '上一级的uuid',`user_uuid` char(36) DEFAULT NULL COMMENT '上传的用户id',`dir` tinyint(1) DEFAULT '0' COMMENT '是否是文件夹',`alien` tinyint(1) DEFAULT '0',`name` varchar(255) DEFAULT NULL COMMENT '文件名称',`md5` varchar(45) DEFAULT NULL COMMENT '文件的md5值',`size` bigint(20) DEFAULT '0' COMMENT '文件大小',`privacy` tinyint(1) DEFAULT '0' COMMENT '文件是否是公有的',`path` varchar(255) DEFAULT NULL,`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='file表';" createMatter := "CREATE TABLE `tank20_matter` (`uuid` char(36) NOT NULL,`puuid` varchar(45) DEFAULT NULL COMMENT '上一级的uuid',`user_uuid` char(36) DEFAULT NULL COMMENT '上传的用户id',`dir` tinyint(1) DEFAULT '0' COMMENT '是否是文件夹',`alien` tinyint(1) DEFAULT '0',`name` varchar(255) DEFAULT NULL COMMENT '文件名称',`md5` varchar(45) DEFAULT NULL COMMENT '文件的md5值',`size` bigint(20) DEFAULT '0' COMMENT '文件大小',`privacy` tinyint(1) DEFAULT '0' COMMENT '文件是否是公有的',`path` varchar(255) DEFAULT NULL,`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='file表';"
db = db.Exec(createMatter) db = db.Exec(createMatter)
if db.Error != nil { if db.Error != nil {
LogPanic(db.Error) LogPanic(db.Error)
@ -49,7 +49,7 @@ func InstallDatabase() {
preference := &Preference{} preference := &Preference{}
hasTable = db.HasTable(preference) hasTable = db.HasTable(preference)
if !hasTable { if !hasTable {
createPreference := "CREATE TABLE `tank10_preference` (`uuid` char(36) NOT NULL,`name` varchar(45) DEFAULT NULL COMMENT '网站名称',`logo_url` varchar(255) DEFAULT NULL,`favicon_url` varchar(255) DEFAULT NULL,`footer_line1` varchar(1024) DEFAULT NULL,`footer_line2` varchar(1024) DEFAULT NULL,`version` varchar(45) DEFAULT NULL,`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='网站偏好设置表';" createPreference := "CREATE TABLE `tank20_preference` (`uuid` char(36) NOT NULL,`name` varchar(45) DEFAULT NULL COMMENT '网站名称',`logo_url` varchar(255) DEFAULT NULL,`favicon_url` varchar(255) DEFAULT NULL,`footer_line1` varchar(1024) DEFAULT NULL,`footer_line2` varchar(1024) DEFAULT NULL,`version` varchar(45) DEFAULT NULL,`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='网站偏好设置表';"
db = db.Exec(createPreference) db = db.Exec(createPreference)
if db.Error != nil { if db.Error != nil {
LogPanic(db.Error) LogPanic(db.Error)
@ -61,7 +61,7 @@ func InstallDatabase() {
hasTable = db.HasTable(session) hasTable = db.HasTable(session)
if !hasTable { if !hasTable {
createSession := "CREATE TABLE `tank10_session` (`uuid` char(36) NOT NULL,`authentication` char(36) DEFAULT NULL COMMENT '认证身份存放在cookie中',`user_uuid` char(36) DEFAULT NULL COMMENT '用户uuid',`ip` varchar(45) DEFAULT NULL COMMENT '用户的ip地址',`expire_time` timestamp NULL DEFAULT NULL,`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='session表';" createSession := "CREATE TABLE `tank20_session` (`uuid` char(36) NOT NULL,`authentication` char(36) DEFAULT NULL COMMENT '认证身份存放在cookie中',`user_uuid` char(36) DEFAULT NULL COMMENT '用户uuid',`ip` varchar(45) DEFAULT NULL COMMENT '用户的ip地址',`expire_time` timestamp NULL DEFAULT NULL,`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='session表';"
db = db.Exec(createSession) db = db.Exec(createSession)
if db.Error != nil { if db.Error != nil {
LogPanic(db.Error) LogPanic(db.Error)
@ -73,7 +73,7 @@ func InstallDatabase() {
hasTable = db.HasTable(uploadToken) hasTable = db.HasTable(uploadToken)
if !hasTable { if !hasTable {
createUploadToken := "CREATE TABLE `tank10_upload_token` (`uuid` char(36) NOT NULL,`user_uuid` char(36) DEFAULT NULL COMMENT '用户uuid',`folder_uuid` char(36) DEFAULT NULL,`matter_uuid` char(36) DEFAULT NULL,`filename` varchar(255) DEFAULT NULL COMMENT '文件后缀名的过滤,可以只允许用户上传特定格式的文件。',`privacy` tinyint(1) DEFAULT '1',`size` bigint(20) DEFAULT '0',`expire_time` timestamp NULL DEFAULT NULL,`ip` varchar(45) DEFAULT NULL COMMENT '消费者的ip',`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='上传的token表';" createUploadToken := "CREATE TABLE `tank20_upload_token` (`uuid` char(36) NOT NULL,`user_uuid` char(36) DEFAULT NULL COMMENT '用户uuid',`folder_uuid` char(36) DEFAULT NULL,`matter_uuid` char(36) DEFAULT NULL,`filename` varchar(255) DEFAULT NULL COMMENT '文件后缀名的过滤,可以只允许用户上传特定格式的文件。',`privacy` tinyint(1) DEFAULT '1',`size` bigint(20) DEFAULT '0',`expire_time` timestamp NULL DEFAULT NULL,`ip` varchar(45) DEFAULT NULL COMMENT '消费者的ip',`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='上传的token表';"
db = db.Exec(createUploadToken) db = db.Exec(createUploadToken)
if db.Error != nil { if db.Error != nil {
LogPanic(db.Error) LogPanic(db.Error)
@ -98,7 +98,7 @@ func InstallDatabase() {
LogPanic("超级管理员邮箱必填!") LogPanic("超级管理员邮箱必填!")
} }
createUser := "CREATE TABLE `tank10_user` (`uuid` char(36) NOT NULL,`role` varchar(45) DEFAULT 'USER',`username` varchar(255) DEFAULT NULL COMMENT '昵称',`password` varchar(255) DEFAULT NULL COMMENT '密码',`email` varchar(45) DEFAULT NULL COMMENT '邮箱',`phone` varchar(45) DEFAULT NULL COMMENT '电话',`gender` varchar(45) DEFAULT 'UNKNOWN' COMMENT '性别,默认未知',`city` varchar(45) DEFAULT NULL COMMENT '城市',`avatar_url` varchar(255) DEFAULT NULL COMMENT '头像链接',`last_time` datetime DEFAULT NULL COMMENT '上次登录使劲按',`last_ip` varchar(45) DEFAULT NULL,`size_limit` int(11) DEFAULT '-1' COMMENT '该账号上传文件的大小限制单位byte。<0 表示不设限制',`status` varchar(45) DEFAULT 'OK',`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户表描述';" createUser := "CREATE TABLE `tank20_user` (`uuid` char(36) NOT NULL,`role` varchar(45) DEFAULT 'USER',`username` varchar(255) DEFAULT NULL COMMENT '昵称',`password` varchar(255) DEFAULT NULL COMMENT '密码',`email` varchar(45) DEFAULT NULL COMMENT '邮箱',`phone` varchar(45) DEFAULT NULL COMMENT '电话',`gender` varchar(45) DEFAULT 'UNKNOWN' COMMENT '性别,默认未知',`city` varchar(45) DEFAULT NULL COMMENT '城市',`avatar_url` varchar(255) DEFAULT NULL COMMENT '头像链接',`last_time` datetime DEFAULT NULL COMMENT '上次登录使劲按',`last_ip` varchar(45) DEFAULT NULL,`size_limit` int(11) DEFAULT '-1' COMMENT '该账号上传文件的大小限制单位byte。<0 表示不设限制',`status` varchar(45) DEFAULT 'OK',`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户表描述';"
db = db.Exec(createUser) db = db.Exec(createUser)
if db.Error != nil { if db.Error != nil {
LogPanic(db.Error) LogPanic(db.Error)

View File

@ -1,39 +1,45 @@
package rest package rest
import ( import (
"io"
"mime/multipart"
"os"
"regexp"
"strings"
"net/http"
"github.com/disintegration/imaging"
"strconv"
"mime"
"path/filepath"
"net/url"
"errors" "errors"
"time"
"fmt" "fmt"
"github.com/disintegration/imaging"
"image"
"io"
"mime"
"mime/multipart"
"net/http"
"net/textproto" "net/textproto"
"net/url"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
) )
//@Service //@Service
type MatterService struct { type MatterService struct {
Bean Bean
matterDao *MatterDao matterDao *MatterDao
userDao *UserDao
} }
//初始化方法 //初始化方法
func (this *MatterService) Init(context *Context) { func (this *MatterService) Init(context *Context) {
//手动装填本实例的Bean. 这里必须要用中间变量方可。 //手动装填本实例的Bean. 这里必须要用中间变量方可。
b := context.GetBean(this.matterDao) b := context.GetBean(this.matterDao)
if b, ok := b.(*MatterDao); ok { if b, ok := b.(*MatterDao); ok {
this.matterDao = b this.matterDao = b
} }
b = context.GetBean(this.userDao)
if b, ok := b.(*UserDao); ok {
this.userDao = b
}
} }
//根据一个文件夹路径找到最后一个文件夹的uuid如果中途出错返回err. //根据一个文件夹路径找到最后一个文件夹的uuid如果中途出错返回err.
@ -122,7 +128,7 @@ func (this *MatterService) Upload(file multipart.File, user *User, puuid string,
} }
//获取文件应该存放在的物理路径的绝对路径和相对路径。 //获取文件应该存放在的物理路径的绝对路径和相对路径。
absolutePath, relativePath := GetUserFilePath(user.Username) absolutePath, relativePath := GetUserFilePath(user.Username, false)
absolutePath = absolutePath + "/" + filename absolutePath = absolutePath + "/" + filename
relativePath = relativePath + "/" + filename relativePath = relativePath + "/" + filename
@ -201,7 +207,7 @@ func (this *MatterService) Crawl(url string, filename string, user *User, puuid
} }
//获取文件应该存放在的物理路径的绝对路径和相对路径。 //获取文件应该存放在的物理路径的绝对路径和相对路径。
absolutePath, relativePath := GetUserFilePath(user.Username) absolutePath, relativePath := GetUserFilePath(user.Username, false)
absolutePath = absolutePath + "/" + filename absolutePath = absolutePath + "/" + filename
relativePath = relativePath + "/" + filename relativePath = relativePath + "/" + filename
@ -243,34 +249,12 @@ func (this *MatterService) Crawl(url string, filename string, user *User, puuid
} }
//图片预处理功能。 //图片预处理功能。
func (this *MatterService) ResizeImage(writer http.ResponseWriter, request *http.Request, matter *Matter) { func (this *MatterService) ResizeImage(request *http.Request, filePath string) *image.NRGBA {
diskFile, err := os.Open(CONFIG.MatterPath + matter.Path) diskFile, err := os.Open(filePath)
this.PanicError(err) this.PanicError(err)
defer diskFile.Close() defer diskFile.Close()
// 防止中文乱码
fileName := url.QueryEscape(matter.Name)
mimeType := GetMimeType(fileName)
writer.Header().Set("Content-Type", mimeType)
//当前的文件是否是图片,只有图片才能处理。
extension := GetExtension(matter.Name)
formats := map[string]imaging.Format{
".jpg": imaging.JPEG,
".jpeg": imaging.JPEG,
".png": imaging.PNG,
".tif": imaging.TIFF,
".tiff": imaging.TIFF,
".bmp": imaging.BMP,
".gif": imaging.GIF,
}
format, ok := formats[extension]
if !ok {
panic("该图片格式不支持处理")
}
imageResizeM := request.FormValue("imageResizeM") imageResizeM := request.FormValue("imageResizeM")
if imageResizeM == "" { if imageResizeM == "" {
imageResizeM = "fit" imageResizeM = "fit"
@ -302,19 +286,14 @@ func (this *MatterService) ResizeImage(writer http.ResponseWriter, request *http
if imageResizeW > 0 { if imageResizeW > 0 {
src, err := imaging.Decode(diskFile) src, err := imaging.Decode(diskFile)
this.PanicError(err) this.PanicError(err)
dst := imaging.Resize(src, imageResizeW, 0, imaging.Lanczos) return imaging.Resize(src, imageResizeW, 0, imaging.Lanczos)
err = imaging.Encode(writer, dst, format)
this.PanicError(err)
} else if imageResizeH > 0 { } else if imageResizeH > 0 {
//将图缩略成高度为100宽度按比例处理。 //将图缩略成高度为100宽度按比例处理。
src, err := imaging.Decode(diskFile) src, err := imaging.Decode(diskFile)
this.PanicError(err) this.PanicError(err)
dst := imaging.Resize(src, 0, imageResizeH, imaging.Lanczos) return imaging.Resize(src, 0, imageResizeH, imaging.Lanczos)
err = imaging.Encode(writer, dst, format)
this.PanicError(err)
} else { } else {
panic("单边缩略必须指定imageResizeW或imageResizeH") panic("单边缩略必须指定imageResizeW或imageResizeH")
} }
@ -323,9 +302,8 @@ func (this *MatterService) ResizeImage(writer http.ResponseWriter, request *http
if imageResizeW > 0 && imageResizeH > 0 { if imageResizeW > 0 && imageResizeH > 0 {
src, err := imaging.Decode(diskFile) src, err := imaging.Decode(diskFile)
this.PanicError(err) this.PanicError(err)
dst := imaging.Fill(src, imageResizeW, imageResizeH, imaging.Center, imaging.Lanczos) return imaging.Fill(src, imageResizeW, imageResizeH, imaging.Center, imaging.Lanczos)
err = imaging.Encode(writer, dst, format)
this.PanicError(err)
} else { } else {
panic("固定宽高,自动裁剪 必须同时指定imageResizeW和imageResizeH") panic("固定宽高,自动裁剪 必须同时指定imageResizeW和imageResizeH")
} }
@ -334,15 +312,47 @@ func (this *MatterService) ResizeImage(writer http.ResponseWriter, request *http
if imageResizeW > 0 && imageResizeH > 0 { if imageResizeW > 0 && imageResizeH > 0 {
src, err := imaging.Decode(diskFile) src, err := imaging.Decode(diskFile)
this.PanicError(err) this.PanicError(err)
dst := imaging.Resize(src, imageResizeW, imageResizeH, imaging.Lanczos) return imaging.Resize(src, imageResizeW, imageResizeH, imaging.Lanczos)
err = imaging.Encode(writer, dst, format)
this.PanicError(err)
} else { } else {
panic("强制宽高缩略必须同时指定imageResizeW和imageResizeH") panic("强制宽高缩略必须同时指定imageResizeW和imageResizeH")
} }
} else {
panic("不支持" + imageResizeM + "处理模式")
}
}
//下载处理后的图片
func (this *MatterService) DownloadImage(writer http.ResponseWriter, fileWriter io.Writer, dstImage *image.NRGBA, filename string) {
// 防止中文乱码
fileName := url.QueryEscape(filename)
mimeType := GetMimeType(fileName)
writer.Header().Set("Content-Type", mimeType)
//当前的文件是否是图片,只有图片才能处理。
extension := GetExtension(filename)
formats := map[string]imaging.Format{
".jpg": imaging.JPEG,
".jpeg": imaging.JPEG,
".png": imaging.PNG,
".tif": imaging.TIFF,
".tiff": imaging.TIFF,
".bmp": imaging.BMP,
".gif": imaging.GIF,
} }
format, ok := formats[extension]
if !ok {
panic("该图片格式不支持处理")
}
err := imaging.Encode(writer, dstImage, format)
this.PanicError(err)
//处理后的图片存放在本地
err = imaging.Encode(fileWriter, dstImage, format)
this.PanicError(err)
} }
// httpRange specifies the byte range to be sent to the client. // httpRange specifies the byte range to be sent to the client.
@ -529,18 +539,20 @@ func (this *MatterService) sumRangesSize(ranges []httpRange) (size int64) {
return return
} }
//文件下载功能。 //文件下载。具有进度功能。
//下载功能参考https://github.com/Masterminds/go-fileserver //下载功能参考https://github.com/Masterminds/go-fileserver
func (this *MatterService) DownloadFile(writer http.ResponseWriter, request *http.Request, matter *Matter) { func (this *MatterService) DownloadFile(writer http.ResponseWriter, request *http.Request, filePath string, filename string) {
diskFile, err := os.Open(CONFIG.MatterPath + matter.Path) diskFile, err := os.Open(filePath)
this.PanicError(err) this.PanicError(err)
defer diskFile.Close() defer diskFile.Close()
//如果是图片或者文本或者视频就直接打开。其余的一律以下载形式返回。 //如果是图片或者文本或者视频就直接打开。其余的一律以下载形式返回。
fileName := url.QueryEscape(matter.Name) fileName := url.QueryEscape(filename)
mimeType := GetMimeType(fileName) mimeType := GetMimeType(fileName)
if strings.Index(mimeType, "image") != 0 && strings.Index(mimeType, "text") != 0 && strings.Index(mimeType, "video") != 0 { if strings.Index(mimeType, "image") != 0 &&
strings.Index(mimeType, "text") != 0 &&
strings.Index(mimeType, "video") != 0 {
writer.Header().Set("content-disposition", "attachment; filename=\""+fileName+"\"") writer.Header().Set("content-disposition", "attachment; filename=\""+fileName+"\"")
} }

View File

@ -3,8 +3,8 @@ package rest
import ( import (
"fmt" "fmt"
"os" "os"
"time"
"path/filepath" "path/filepath"
"time"
) )
//判断文件或文件夹是否已经存在 //判断文件或文件夹是否已经存在
@ -89,13 +89,17 @@ func GetConfPath() string {
//获取某个用户文件应该存放的位置。这个是相对GetFilePath的路径 //获取某个用户文件应该存放的位置。这个是相对GetFilePath的路径
//例如:/zicla/2006-01-02/1510122428000 //例如:/zicla/2006-01-02/1510122428000
func GetUserFilePath(username string) (string, string) { func GetUserFilePath(username string, cache bool) (string, string) {
now := time.Now() now := time.Now()
datePath := now.Format("2006-01-02") datePath := now.Format("2006-01-02")
//毫秒时间戳 //毫秒时间戳
timestamp := now.UnixNano() / 1e6 timestamp := now.UnixNano() / 1e6
//如果是缓存文件夹那么统一放在cache这个文件夹下面
if cache {
datePath = fmt.Sprintf("cache/%s", datePath)
}
filePath := CONFIG.MatterPath filePath := CONFIG.MatterPath
absolutePath := fmt.Sprintf("%s/%s/%s/%d", filePath, username, datePath, timestamp) absolutePath := fmt.Sprintf("%s/%s/%s/%d", filePath, username, datePath, timestamp)
relativePath := fmt.Sprintf("/%s/%s/%d", username, datePath, timestamp) relativePath := fmt.Sprintf("/%s/%s/%d", username, datePath, timestamp)