Browse Source

Merge branch 'dev' of http://git.ycjcjy.com/SpaceOfCheng/services into dev

胡轶钦 6 years ago
parent
commit
4b1da1ee6a
2 changed files with 79 additions and 0 deletions
  1. 25
    0
      controllers/file.go
  2. 54
    0
      utils/zip.go

+ 25
- 0
controllers/file.go View File

@@ -121,3 +121,28 @@ func (c *BaseController) uploadStringToAliOSS(fStr string) (string, error) {
121 121
 
122 122
 	return fileURL, nil
123 123
 }
124
+
125
+// SaveNetFilesToZip 压缩远程文件并下载
126
+func (c *BaseController) SaveNetFilesToZip(files []utils.NetFile, zf string) {
127
+	var buf bytes.Buffer
128
+
129
+	err := utils.ZipNetFiles(files, &buf)
130
+	if err != nil {
131
+		c.ResponseError(errors.New("下载 zip 文件失败"))
132
+	}
133
+
134
+	c.Ctx.Output.Header("Content-Disposition", "attachment; filename="+url.QueryEscape(zf))
135
+	c.Ctx.Output.Header("Content-Description", "File Transfer")
136
+	c.Ctx.Output.ContentType("application/zip")
137
+	c.Ctx.Output.Header("Content-Transfer-Encoding", "binary")
138
+	c.Ctx.Output.Header("Expires", "0")
139
+	c.Ctx.Output.Header("Cache-Control", "must-revalidate")
140
+	c.Ctx.Output.Header("Pragma", "public")
141
+
142
+	r := bytes.NewReader(buf.Bytes())
143
+	http.ServeContent(c.Ctx.ResponseWriter, c.Ctx.Request, zf, time.Now().Local(), r)
144
+
145
+	c.destroyContext(true)
146
+	c.StopRun()
147
+
148
+}

+ 54
- 0
utils/zip.go View File

@@ -0,0 +1,54 @@
1
+package utils
2
+
3
+import (
4
+	"archive/zip"
5
+	"compress/flate"
6
+	"io"
7
+	"io/ioutil"
8
+	"net/http"
9
+)
10
+
11
+// NetFile 远程文件
12
+type NetFile struct {
13
+	Name string
14
+	URI  string
15
+}
16
+
17
+// ZipNetFiles 压缩远程文件
18
+func ZipNetFiles(files []NetFile, w io.Writer) error {
19
+	if files == nil || len(files) == 0 {
20
+		return nil
21
+	}
22
+
23
+	z := zip.NewWriter(w)
24
+	defer z.Close()
25
+
26
+	z.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) {
27
+		return flate.NewWriter(out, flate.BestCompression)
28
+	})
29
+
30
+	for _, f := range files {
31
+		resp, err := http.Get(f.URI)
32
+		if err != nil {
33
+			LogError("获取远程文件失败: ", err)
34
+			return err
35
+		}
36
+
37
+		dt, err := ioutil.ReadAll(resp.Body)
38
+		defer resp.Body.Close()
39
+		if err != nil {
40
+			LogError("读取远程文件内容失败: ", err)
41
+			return err
42
+		}
43
+
44
+		fd, err := z.Create(f.Name)
45
+		if err != nil {
46
+			LogError("压缩远程文件失败: ", err)
47
+			return err
48
+		}
49
+
50
+		fd.Write(dt)
51
+	}
52
+
53
+	return nil
54
+}