GIN试玩:文件上传下载(图片和压缩文件)
package Controller
import (
"archive/zip"
"fmt"
"github.com/gin-gonic/gin"
"go-service/src/Config"
"io"
"os"
"path/filepath"
"strings"
)
type UploadController struct {
}
var UploadControl = &UploadController{}
func (*UploadController) UploadImage(c *gin.Context) {
dir := Config.StaticUrl // 配置文件中的静态资源路径
file, _ := c.FormFile("file")
filename := RandStr(40) + ".jpg"
//将文件保存到本地服务器的指定位置
if err := c.SaveUploadedFile(file, dir+filename); err != nil {
ResponseError(c, "文件上传失败")
} else {
ResponseSuccess(c, filename)
}
}
// 某些文件的执行依赖于其他文件,比如3D模型,所以需要通过ZIP的方式上传,同时要指定执行文件的名称
// 先将ZIP保存,然后解压,最后删除保存的ZIP
func (*UploadController) UploadZipFile(c *gin.Context) {
dir := Config.StaticUrl
file, _ := c.FormFile("file")
name := c.PostForm("name") // 执行文件名称
filename := RandStr(40)
//将文件保存到本地服务器的指定位置
if err := c.SaveUploadedFile(file, dir+filename+".zip"); err != nil {
ResponseError(c, "文件上传失败")
} else {
det, err := Unzip(filename+".zip", filename, name) // 解压
if err != nil {
ResponseError(c, "文件上传失败")
return
}
UploadControl.RemoveFile(filename + ".zip") // 删除zip
if det == "" {
ResponseError(c, "文件名称错误")
} else {
ResponseSuccess(c, det)
}
}
}
// 解压
func Unzip(zipFile string, destDir string, exec string) (string, error) {
dir := Config.StaticUrl
dst := ""
zipReader, err := zip.OpenReader(dir + zipFile)
if err != nil {
return dst, err
}
defer zipReader.Close()
for _, f := range zipReader.File {
fpath := filepath.Join(dir+destDir, f.Name)
if f.FileInfo().IsDir() {
os.MkdirAll(fpath, os.ModePerm)
} else {
fmt.Println(f.Name, exec)
if strings.Contains(f.Name, exec) {
dst = filepath.Join(destDir, f.Name)
}
if err = os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil {
return dst, err
}
inFile, err := f.Open()
if err != nil {
return dst, err
}
outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
if err != nil {
return dst, err
}
_, err = io.Copy(outFile, inFile)
if err != nil {
return dst, err
}
outFile.Close()
inFile.Close()
}
}
return dst, nil
}
func (*UploadController) DownloadFile(c *gin.Context) {
dir := Config.StaticUrl
name := c.Query("f")
arr := strings.Split(name, "/") // 路径默认斜杠,为了兼容Linux
for _, s := range arr {
dir = filepath.Join(dir, s)
}
c.File(dir)
}
func (*UploadController) RemoveFile(filename string) {
dir := Config.StaticUrl
err := os.RemoveAll(filepath.Join(dir, filename))
if err != nil {
fmt.Println(err.Error())
}
}