我想要提供即时创建的.ZIP文件,而不必将其写入磁盘(I/O会降低性能)并通过HTTP将其提供给客户端.
这是我第一次尝试这个:
func ZipServe(W http.ResponseWriter, R *http.Request) {
buf := new(bytes.Buffer)
writer := zip.NewWriter(buf)
// for the sake of this demonstration, this is the data I will zip
data := ioutil.ReadFile("randomfile.jpg")
f, err := writer.Create("randomfile.jpg")
if err != nil {
fmt.Println(err)
}
_, err = f.Write(data)
if err != nil {
fmt.Println(err)
}
io.Copy(W, buf)
err := writer.Close()
if err != nil {
fmt.Println(err)
}
}
Run Code Online (Sandbox Code Playgroud)
这并不好,因为.ZIP在下载后最终会被破坏.我想这个问题与io.Copy有关; 我应该使用不同的方法吗?
我觉得这很有趣,只是为了测试得出了这个:
http://play.golang.org/p/JKAde2jbR3
package main
import (
"archive/zip"
"bytes"
"fmt"
"io/ioutil"
"log"
"net/http"
)
func zipHandler(w http.ResponseWriter, r *http.Request) {
filename := "randomfile.jpg"
buf := new(bytes.Buffer)
writer := zip.NewWriter(buf)
data, err := ioutil.ReadFile(filename)
if err != nil {
log.Fatal(err)
}
f, err := writer.Create(filename)
if err != nil {
log.Fatal(err)
}
_, err = f.Write([]byte(data))
if err != nil {
log.Fatal(err)
}
err = writer.Close()
if err != nil {
log.Fatal(err)
}
w.Header().Set("Content-Type", "application/zip")
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s.zip\"", filename))
//io.Copy(w, buf)
w.Write(buf.Bytes())
}
func main() {
http.HandleFunc("/zip", zipHandler)
http.ListenAndServe(":8080", nil)
}
Run Code Online (Sandbox Code Playgroud)
我只是添加一些标题,如Content-Type 和Content-Disposition.
而不是使用io.Copy(w, buf)我写的直接w.Write(buf.Bytes())想知道这是否更好?可能更有经验的用户可以澄清这一点.
| 归档时间: |
|
| 查看次数: |
2058 次 |
| 最近记录: |