我想提供一个可下载的文件,但当我测试它时,我可以下载文件,但下载的文件是空白的。我在IDE中检查了文件有内容,但下载的文件是空的,甚至我得到的文件大小都是0。请帮帮忙。
文件信息:- File是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))
}发布于 2020-09-08 17:41:26
好了,我弄明白了,我正在使用"defer writer.flush()“来创建csv文件,在同一个函数中,我调用了上面的发送器函数,因为延迟文件没有保存,它正在发送空白文件,并且在发送空白文件之后,它正在保存文件。因此,我删除了defer并将(writer.flush )函数放在我想要保存文件的位置。保存文件后,我调用了我的发送器函数,它起作用了。
https://stackoverflow.com/questions/63781184
复制相似问题