【问题标题】:HTTP downloadable file servingHTTP 可下载文件服务
【发布时间】: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


【解决方案1】:

好的,我发现我正在使用“defer writer.flush()”来创建 csv 文件,并且在相同的函数中我调用了发送方函数,由于延迟文件没有保存并且它正在发送空白文件并且在发送之后空白文件它正在保存文件。因此,我删除了 defer 并将(writer.flush)函数放在我想保存文件的位置。保存文件后,我调用了我的发件人函数并且它起作用了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-23
    • 2011-06-03
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多