我想提供一个可下载的文件,但是当我测试它时,我可以下载文件但下载的文件是空白的。我在 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))
}
最佳答案
好的,我发现我正在使用“defer writer.flush()”创建csv文件,并且在相同的函数中我调用了发送者函数,由于延迟文件没有保存并且它正在发送空白文件并且在发送空白文件之后它正在保存文件。因此,我删除了 defer 并将(writer.flush)函数放在我想保存文件的位置。保存文件后,我调用了我的发件人函数并且它起作用了。
关于HTTP 可下载文件服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63781184/