首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >HTTP可下载文件服务

HTTP可下载文件服务
EN

Stack Overflow用户
提问于 2020-09-08 00:24:55
回答 1查看 108关注 0票数 0

我想提供一个可下载的文件,但当我测试它时,我可以下载文件,但下载的文件是空白的。我在IDE中检查了文件有内容,但下载的文件是空的,甚至我得到的文件大小都是0。请帮帮忙。

文件信息:- File是csv,它只包含一行字段名。

代码语言:javascript
复制
 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))



}
EN

回答 1

Stack Overflow用户

发布于 2020-09-08 17:41:26

好了,我弄明白了,我正在使用"defer writer.flush()“来创建csv文件,在同一个函数中,我调用了上面的发送器函数,因为延迟文件没有保存,它正在发送空白文件,并且在发送空白文件之后,它正在保存文件。因此,我删除了defer并将(writer.flush )函数放在我想要保存文件的位置。保存文件后,我调用了我的发送器函数,它起作用了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63781184

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档