我有一个处理函数,如下所示:
func DownloadFileHandler(w http.ResponseWriter, r *http.Request) {
SetResponseHeaders(w, r)
if r.Method == "OPTIONS" {
return
}
var err error
var responseCode int = http.StatusBadRequest
vars := mux.Vars(r)
file := vars["file"]
var n int64 = 0
var reader io.Reader
Filename := "images/" + file
f, err := os.Open(Filename)
if err != nil {
err = errors.New("File not found")
goto Error
}
reader = bufio.NewReader(f)
settings.WriteDebugLog(time.Now())
n, err = io.Copy(w, reader) // this takes a long time if the file is large
settings.WriteDebugLog(time.Now())
settings.WriteDebugLog(n / 1024 / 1024)
responseCode = http.StatusOK
settings.WriteLog(r, responseCode, nil, GetCurrentFuncName())
return
Error:
WriteErrorResponse(w, responseCode, err)
settings.WriteLog(r, responseCode, err, GetCurrentFuncName())
}
但是如果它是一个大文件(超过1GB),io.Copy需要相当长的时间(最好的情况:下面显示的1G 13秒)并且浏览器中的下载过程直到io.Copy完成。有没有办法更有效地实现我的目标?我希望在发送下载请求后立即在我的浏览器中显示下载过程。
2017/05/16 22:32:29 Debug: 2017-05-16 22:32:29.967499719 +0900 JST
2017/05/16 22:32:36 Debug: 2017-05-16 22:32:36.980914163 +0900 JST
2017/05/16 22:32:36 Debug: 1097
我尝试使用“go io.Copy”调用io.Copy,然后下载过程很快显示,但文件大小为0.