亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 Swag golang 庫下載文件?

如何使用 Swag golang 庫下載文件?

Go
慕婉清6462132 2022-07-04 16:48:32
我正在嘗試在golang中使用gin-gonic制作一個REST API ,它從GET請求中獲取一些路徑參數并下載該文件。curl命令可以正常工作。但是,當我添加swagger UI文檔時,如果下載的文件是文本或圖像,它只是顯示在該網頁中,但我看不到任何下載選項。如果我輸入視頻文件的路徑,瀏覽器會掛起。此外,要下載的文件的MIME類型由gin-gonic正確確定。但是,要通過swagger UI 界面下載文件,我使用的是硬編碼的 @Accept和@Produce swagger UI 注釋注釋。理想情況下,它應該自動確定 MIME 類型。目前,響應類型被列為下拉列表,我可以在其中獲得各種選項。我需要它來自動檢測正確的 MIME 類型并盡可能顯示下載按鈕我的 GET 請求代碼是:// DownloadObject godoc// @Summary Download object// @Description Download object// @Produce application/json// @Produce text/plain// @Produce application/octet-stream// @Produce video/mp4// @Produce image/png// @Produce image/jpeg// @Produce image/gif// @Param rootPath path string true "Root Path"// @Param filePath path string true "File Path"// @Header 200 {string} Token "qwerty"// @Router /transfer/{rootPath}/{filePath} [get]func DownloadObject(c *gin.Context) {    // Get rootPath & filePath from GET request    rootPath := c.Param("rootPath")    filePath := c.Param("filePath")    // Some code to get an io.Reader object "download"    _, err = io.Copy(c.Writer, download)    if err != nil {        c.Status(http.StatusInternalServerError)        log.Print(err)        return    }    err = download.Close()    if err != nil {        c.Status(http.StatusInternalServerError)        log.Print(err)        return    }        c.Writer.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=%", filePath))    c.Writer.Header().Add("Content-Type", c.GetHeader("Content-Type"))    // Object download completed & closed successfully}我在這里錯過了什么嗎?
查看完整描述

1 回答

?
眼眸繁星

TA貢獻1873條經驗 獲得超9個贊

您在瀏覽器接收到文件后添加標題,將它們移到之前io.Copy以使它們生效。此外,您在通話中有一個錯誤的格式動詞(只是%),fmt.Sprintf請使用%q:


func DownloadObject(c *gin.Context) {


    // Get rootPath & filePath from GET request

    rootPath := c.Param("rootPath")

    filePath := c.Param("filePath")


    // ...


    // Add headers to the response

    c.Writer.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=%q", filePath))

    c.Writer.Header().Add("Content-Type", c.GetHeader("Content-Type"))



    _, err = io.Copy(c.Writer, download)

    if err != nil {

        c.Status(http.StatusInternalServerError)

        log.Print(err)

        return

    }


    err = download.Close()

    if err != nil {

        c.Status(http.StatusInternalServerError)

        log.Print(err)

        return

    }

    

}


查看完整回答
反對 回復 2022-07-04
  • 1 回答
  • 0 關注
  • 154 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號