Skip to content

Instantly share code, notes, and snippets.

@xieyuschen
Last active March 20, 2024 15:19
Show Gist options
  • Save xieyuschen/795ab3a78713975fdd5a28afe60972d7 to your computer and use it in GitHub Desktop.
Save xieyuschen/795ab3a78713975fdd5a28afe60972d7 to your computer and use it in GitHub Desktop.
Gin: download file with an simple api

Gin: download file with an simple api

func DownloadLicense(ctx *gin.Context) {
	content:="Download file here happliy"
	fileName := "hello.txt"
	ctx.Header("Content-Disposition", "attachment; filename="+fileName)
	ctx.Header("Content-Type", "application/text/plain")
	ctx.Header("Accept-Length", fmt.Sprintf("%d", len(content)))
	ctx.Writer.Write([]byte(content))
	ctx.JSON(http.StatusOK, gin.H{
		"msg": "Download file successfully",
	})
}
@novialriptide
Copy link

이것은 매우 도움이 돼요. 감사합니다!!

@mohamadkenway
Copy link

Thanks it works

@pivaldi
Copy link

pivaldi commented Mar 20, 2024

Hi,

There is no file in the example.
The simplest way to attach a file is

func DownloadLicense(ctx *gin.Context) {
	ctx.FileAttachment(filepath, filenameDisplayed)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment