golang实现http server提供文件下载功能
func FileDownload(w http.ResponseWriter, r *http.Request) {
filename := get_filename_from_request(r)
file, _ := os.Open(filename)
defer file.Close()
fileHeader := make([]byte, 512)
file.Read(fileHeader)
fileStat, _ := file.Stat()
w.Header().Set("Content-Disposition", "attachment; filename=" + filename)
w.Header().Set("Content-Type", http.DetectContentType(fileHeader))
w.Header().Set("Content-Length", strconv.FormatInt(fileStat.Size(), 10))
file.Seek(0, 0)
io.Copy(w, file)
return
}
网友评论