【发布时间】:2020-12-26 02:07:26
【问题描述】:
我想提供一个可下载的文件,但是当我测试它时,我能够下载文件但下载的文件是空白的。我在 IDE 中检查了文件有内容,但下载的文件是空白的,甚至我的文件大小为 0。请帮忙。
文件信息:- 文件是 csv,它只包含一行字段名称。
func SendFileToClient(w http.ResponseWriter,r *http.Request,file string){
downloadBytes, err := ioutil.ReadFile(file)
fmt.Println("file to be sent ",file)
if err != nil {
fmt.Printf("unable to download the file: %v", err)
}
mime := http.DetectContentType(downloadBytes)
fileSize := len(string(downloadBytes))
fmt.Println("mime is ",mime ," filesize ",fileSize)
//Generate the server headers
w.Header().Set("Content-Type", "octet-stream")
w.Header().Set("Content-Disposition", "attachment; filename="+file+"")
w.Header().Set("Expires", "0")
w.Header().Set("Content-Transfer-Encoding", "binary")
w.Header().Set("Content-Length", strconv.Itoa(fileSize))
w.Header().Set("Content-Control", "private, no-transform, no-store, must-revalidate")
//// force it down the client's.....
http.ServeContent(w, r, file, time.Now(), bytes.NewReader(downloadBytes))
}
【问题讨论】:
-
您确定 ioutil.ReadFile 不返回错误吗?打印错误后,您就像什么都没发生一样继续前进。
-
不,它不会返回任何错误,但是ioutil.ReadFile函数正在读取0字节,即使路径是正确的。
标签: http go http-headers