进阶 www.iris-go.com 2026-10-20 02:39:14 · 15 阅读
第6章 Iris框架:从上下文发送文件
### 第6章:从上下文发送文件
以下 Go 语言接口定义展示了如何从 Iris 框架的上下文(Context)中发送文件。
`SendFile` 方法将文件作为附件发送给客户端,客户端会将其下载并保存到本地。注意,可以通过调用 `ctx.CompressWriter(true)` 或使用中间件 `app.Use(iris.Compression)` 来注册压缩功能。如果希望将文件作为页面资源而非附件提供服务,请使用 `ServeFile`。
```go
// SendFile 将文件作为附件发送,客户端会下载并保存在本地。
// 注意:可通过 `ctx.CompressWriter(true)` 或 `app.Use(iris.Compression)` 启用压缩。
// 若需将文件作为页面资源提供,请使用 `ServeFile`。
SendFile(filename string, destinationName string) error
// SendFileWithRate 功能与 `SendFile` 类似,但可以在向客户端写入文件时控制读写速度。
SendFileWithRate(src, destName string, limit float64, burst int) error
```
#### 使用示例
强制向客户端发送文件:
```go
func handler(ctx iris.Context) {
src := "./files/first.zip"
ctx.SendFile(src, "client.zip")
}
```
将下载速度限制在约 50KB/s,突发(burst)容量设为 100KB:
```go
func handler(ctx iris.Context) {
src := "./files/big.zip"
// 可选:留空字符串可让框架根据 src 自动解析文件名。
dest := ""
limit := 50.0 * iris.KB
burst := 100 * iris.KB
ctx.SendFileWithRate(src, dest, limit, burst)
}
```
go// ServeContent 使用提供的 ReadSeeker 中的内容来响应请求。相比 io.Copy,
// ServeContent 的主要优势在于它能正确处理 Range 请求、设置 MIME 类型,
// 并处理 If-Match、If-Unmodified-Since、If-None-Match、If-Modified-Since
// 和 If-Range 请求。
//
// 如果响应的 Content-Type 头未设置,ServeContent 会先尝试根据 name 的
// 文件扩展名推断类型。
//
// name 其他情况下不使用;特别是它可以为空,且永远不会随响应发送。
//
// 如果 modtime 不是零值时间或 Unix 纪元,ServeContent 会在响应中通过
// Last-Modified 头包含它。如果请求包含 If-Modified-Since 头,
// ServeContent 会用 modtime 判断是否需要发送内容。
//
// 内容的 Seek 方法必须可用:ServeContent 会通过 seek 到内容末尾来确定其大小。
//
// 如果调用方已按 RFC 7232 第 2.3 节的格式设置了 w 的 ETag 头,
// ServeContent 会用它来处理 If-Match、If-None-Match 或 If-Range 请求。
//
// 注意 *os.File 实现了 io.ReadSeeker 接口。
// 注意可以通过 `ctx.CompressWriter(true)` 或 `app.Use(iris.Compression)`
// 注册压缩功能。
ServeContent(content io.ReadSeeker, filename string, modtime time.Time)
// ServeFileWithRate 与 `ServeContent` 相同,但可以限流,控制向客户端
// 读取并写入 "content" 的速度。
ServeContentWithRate(content io.ReadSeeker, filename string, modtime time.Time, limit float64, burst int)
// ServeFile 用指定文件或目录的内容来响应请求。
//
// 如果提供的文件或目录名是相对路径,将相对于当前目录解释,且可能
// 向上追溯到父目录。如果提供的名称来自用户输入,应在调用 `ServeFile`
// 前进行安全处理。
//
// 当你想提供 css、javascript 等静态资源时使用它。如果需要客户端确认
// 并保存文件,请改用 `SendFile`。
// 注意可以通过 `ctx.CompressWriter(true)` 或 `app.Use(iris.Compression)`
// 注册压缩功能。
ServeFile(filename string) error
// ServeFileWithRate 与 `ServeFile` 相同,但可以限流,控制向客户端
// 读取并写入文件的速度。
ServeFileWithRate(filename string, limit float64, burst int) error1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
func handler(ctx iris.Context) 的使用示例如下: ctx.ServeFile("./public/main.js") }1
2
3
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
func handler(ctx iris.Context) 的使用示例如下: ctx.ServeFile("./public/main.js") }1
2
3