温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Golang Gin框架实现文件下载功能的示例代码怎么写

发布时间:2021-12-09 15:07:53 来源:亿速云 阅读:424 作者:柒染 栏目:开发技术

这期内容当中小编将会给大家带来有关Golang Gin框架实现文件下载功能的示例代码怎么写,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

Layui框架实现文件上传

基本的思路就是随便创建一个元素,然后使用layui的upload组件对创建的元素进行渲染,详见代码

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="jquery-3.5.0.min.js" type="text/javascript"></script> <!-- jquery包,记得替换为你本地的路径 -->

    <link rel="stylesheet" href="layui/css/layui.css" rel="external nofollow" > <!--layui框架的样式库 同样你本地的路径 -->
    <script src="pkg/layui/layui.js"></script><!--enmmm 没错,路径-->
</head>	
<body>
<!-- 这里我是用的a标签,当然你可以使用别的 label、button等均可-->
 <a href="javascript:(0);" rel="external nofollow"  id="attachment-upload">+添加附件</a>
</body>
<script>
	//以layui.js的方式引入使用时需要手动加载layui的组件
	layui.use(['layer','upload'],function(){ // PS:个人理解,该行只是为了引入layui框架的组件,html文件加载完毕后执行,内部的代码和直接写在script标签内没啥区别,只是可以在代码中使用layer了
	// 此处引入layer只是为了打印一些东西
		var layer = layui.layer,
		upload = layui.upload;
		
	// 渲染元素,使其支持文件上传
	// 详情请移步 https://www.layui.com/doc/modules/upload.html
	// https://www.layui.com/demo/upload.html
	 upload.render({
            elem: '#attachment-upload', // 感觉利用了jquery的id选择器,这里用#id(上传附件的标签、按钮值类型元素id)就可以了
            url: dev_url + "fc/upload", // 后端接收上传文件的接口地址
            headers: {   // 这里官方文档中没有,是在请求后端接口时在request header中增加一些请求参数,实测可行
                'api_token': uInfo
            },
            accept: 'file', // 这里可以限定支持上传文件的类型,详见文档
            done: function (res) { // 调用后端上传文件接口后的返回
           // 这里解析下后端的返回字段,具体怎么着看业务吧
                if (res.success == false) {
                    layer.msg("上传文件失败!" + res.msg);
                }
        });
})
</script>
</html>

PS:注意下使用layui上传文件的请求格式为multiply/form-data,参数为file,(binary)格式

Golang Gin框架实现文件下载功能的示例代码怎么写

Gin框架获取前端上传的文件

func UploadFileControl(c *gin.Context) {
	logrus.Infof("[UploadFileControl] user_id =%d", userId)
	// GIN框架获取前端上传文件
	// 这里的参数其实是上传文件时的字段名,也就是上面图片中的file,如果前端是自己定义的其他字段名,需要替换下
	uploadFile, fileHeader, err := c.Request.FormFile("file")
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"success": false,
			"msg":     "获取文件信息失败!" + err.Error(),
		})
	}
	if uploadFile != nil { // 记得及时关闭文件,避免内存泄漏
		defer uploadFile.Close()
	}

// 读取上传文件的内容
// 其实这里直接读取所有不太合理,如果文件过大时会占用很多内存,可以考虑使用缓冲区读取
	fileContent, err := ioutil.ReadAll(uploadFile)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"success": false,
			"msg":     "读取文件内容失败!" + err.Error(),
		})
	}

// 接受到文件后的处理方式,可以保存到本地,也可以上传到文件对象,看自己了
	/*fileId, err := oss.GetOssClient().UploadFile(userId, fileHeader.Filename, fileContent)
	if err != nil {
		logrus.Errorf("[UploadFile] error,user_id = %d,err_msg= %s", userId, err.Error())
		c.JSON(http.StatusOK, gin.H{
			"success": false,
			"msg":     "上传文件失败!请稍后再试",
		})
	}*/

// 这里向前端返回下上传成功的信息
	c.JSON(http.StatusOK, gin.H{
		"success":   true,
		"msg":       "",
	})
}

Gin框架的文件下载

        Response Header中的Content-Type指定了服务器端返回数据的类型,浏览器自己是可以处理这些类型的,当返回的数据为文件类型时,浏览器会自行下载。具体的类型和content-type的对应方式可见

文件扩展名Content-Type(Mime-Type)文件扩展名Content-Type(Mime-Type)
.*( 二进制流,不知道下载文件类型)application/octet-stream.tifimage/tiff
.001application/x-001.301application/x-301
.323text/h423.906application/x-906
.907drawing/907.a11application/x-a11
.acpaudio/x-mei-aac.aiapplication/postscript
.aifaudio/aiff.aifcaudio/aiff
.aiffaudio/aiff.anvapplication/x-anv
.asatext/asa.asfvideo/x-ms-asf
.asptext/asp.asxvideo/x-ms-asf
.auaudio/basic.avivideo/avi
.awfapplication/vnd.adobe.workflow.biztext/xml
.bmpapplication/x-bmp.botapplication/x-bot
.c4tapplication/x-c4t.c90application/x-c90
.calapplication/x-cals.catapplication/vnd.ms-pki.seccat
.cdfapplication/x-netcdf.cdrapplication/x-cdr
.celapplication/x-cel.cerapplication/x-x509-ca-cert
.cg4application/x-g4.cgmapplication/x-cgm
.citapplication/x-cit.classjava/*
.cmltext/xml.cmpapplication/x-cmp
.cmxapplication/x-cmx.cotapplication/x-cot
.crlapplication/pkix-crl.crtapplication/x-x509-ca-cert
.csiapplication/x-csi.csstext/css
.cutapplication/x-cut.dbfapplication/x-dbf
.dbmapplication/x-dbm.dbxapplication/x-dbx
.dcdtext/xml.dcxapplication/x-dcx
.derapplication/x-x509-ca-cert.dgnapplication/x-dgn
.dibapplication/x-dib.dllapplication/x-msdownload
.docapplication/msword.dotapplication/msword
.drwapplication/x-drw.dtdtext/xml
.dwfModel/vnd.dwf.dwfapplication/x-dwf
.dwgapplication/x-dwg.dxbapplication/x-dxb
.dxfapplication/x-dxf.ednapplication/vnd.adobe.edn
.emfapplication/x-emf.emlmessage/rfc822
.enttext/xml.epiapplication/x-epi
.epsapplication/x-ps.epsapplication/postscript
.etdapplication/x-ebx.exeapplication/x-msdownload
.faximage/fax.fdfapplication/vnd.fdf
.fifapplication/fractals.fotext/xml
.frmapplication/x-frm.g4application/x-g4
.gbrapplication/x-gbr.application/x-
.gifimage/gif.gl2application/x-gl2
.gp4application/x-gp4.hglapplication/x-hgl
.hmrapplication/x-hmr.hpgapplication/x-hpgl
.hplapplication/x-hpl.hqxapplication/mac-binhex40
.hrfapplication/x-hrf.htaapplication/hta
.htctext/x-component.htmtext/html
.htmltext/html.htttext/webviewhtml
.htxtext/html.icbapplication/x-icb
.icoimage/x-icon.icoapplication/x-ico
.iffapplication/x-iff.ig4application/x-g4
.igsapplication/x-igs.iiiapplication/x-iphone
.imgapplication/x-img.insapplication/x-internet-signup
.ispapplication/x-internet-signup.IVFvideo/x-ivf
.javajava/*.jfifimage/jpeg
.jpeimage/jpeg.jpeapplication/x-jpe
.jpegimage/jpeg.jpgimage/jpeg
.jpgapplication/x-jpg.jsapplication/x-javascript
.jsptext/html.la1audio/x-liquid-file
.larapplication/x-laplayer-reg.latexapplication/x-latex
.lavsaudio/x-liquid-secure.lbmapplication/x-lbm
.lmsffaudio/x-la-lms.lsapplication/x-javascript
.ltrapplication/x-ltr.m1vvideo/x-mpeg
.m2vvideo/x-mpeg.m3uaudio/mpegurl
.m4evideo/mpeg4.macapplication/x-mac
.manapplication/x-troff-man.mathtext/xml
.mdbapplication/msaccess.mdbapplication/x-mdb
.mfpapplication/x-shockwave-flash.mhtmessage/rfc822
.mhtmlmessage/rfc822.miapplication/x-mi
.midaudio/mid.midiaudio/mid
.milapplication/x-mil.mmltext/xml
.mndaudio/x-musicnet-download.mnsaudio/x-musicnet-stream
.mochaapplication/x-javascript.movievideo/x-sgi-movie
.mp1audio/mp1.mp2audio/mp2
.mp2vvideo/mpeg.mp3audio/mp3
.mp4video/mpeg4.mpavideo/x-mpg
.mpdapplication/vnd.ms-project.mpevideo/x-mpeg
.mpegvideo/mpg.mpgvideo/mpg
.mpgaaudio/rn-mpeg.mppapplication/vnd.ms-project
.mpsvideo/x-mpeg.mptapplication/vnd.ms-project
.mpvvideo/mpg.mpv2video/mpeg
.mpwapplication/vnd.ms-project.mpxapplication/vnd.ms-project
.mtxtext/xml.mxpapplication/x-mmxp
.netimage/pnetvue.nrfapplication/x-nrf
.nwsmessage/rfc822.odctext/x-ms-odc
.outapplication/x-out.p10application/pkcs10
.p12application/x-pkcs12.p7bapplication/x-pkcs7-certificates
.p7capplication/pkcs7-mime.p7mapplication/pkcs7-mime
.p7rapplication/x-pkcs7-certreqresp.p7sapplication/pkcs7-signature
.pc5application/x-pc5.pciapplication/x-pci
.pclapplication/x-pcl.pcxapplication/x-pcx
.pdfapplication/pdf.pdfapplication/pdf
.pdxapplication/vnd.adobe.pdx.pfxapplication/x-pkcs12
.pglapplication/x-pgl.picapplication/x-pic
.pkoapplication/vnd.ms-pki.pko.plapplication/x-perl
.plgtext/html.plsaudio/scpls
.pltapplication/x-plt.pngimage/png
.pngapplication/x-png.potapplication/vnd.ms-powerpoint
.ppaapplication/vnd.ms-powerpoint.ppmapplication/x-ppm
.ppsapplication/vnd.ms-powerpoint.pptapplication/vnd.ms-powerpoint
.pptapplication/x-ppt.prapplication/x-pr
.prfapplication/pics-rules.prnapplication/x-prn
.prtapplication/x-prt.psapplication/x-ps
.psapplication/postscript.ptnapplication/x-ptn
.pwzapplication/vnd.ms-powerpoint.r3ttext/vnd.rn-realtext3d
.raaudio/vnd.rn-realaudio.ramaudio/x-pn-realaudio
.rasapplication/x-ras.ratapplication/rat-file
.rdftext/xml.recapplication/vnd.rn-recording
.redapplication/x-red.rgbapplication/x-rgb
.rjsapplication/vnd.rn-realsystem-rjs.rjtapplication/vnd.rn-realsystem-rjt
.rlcapplication/x-rlc.rleapplication/x-rle
.rmapplication/vnd.rn-realmedia.rmfapplication/vnd.adobe.rmf
.rmiaudio/mid.rmjapplication/vnd.rn-realsystem-rmj
.rmmaudio/x-pn-realaudio.rmpapplication/vnd.rn-rn_music_package
.rmsapplication/vnd.rn-realmedia-secure.rmvbapplication/vnd.rn-realmedia-vbr
.rmxapplication/vnd.rn-realsystem-rmx.rnxapplication/vnd.rn-realplayer
.rpimage/vnd.rn-realpix.rpmaudio/x-pn-realaudio-plugin
.rsmlapplication/vnd.rn-rsml.rttext/vnd.rn-realtext
.rtfapplication/msword.rtfapplication/x-rtf
.rvvideo/vnd.rn-realvideo.samapplication/x-sam
.satapplication/x-sat.sdpapplication/sdp
.sdwapplication/x-sdw.sitapplication/x-stuffit
.slbapplication/x-slb.sldapplication/x-sld
.slkdrawing/x-slk.smiapplication/smil
.smilapplication/smil.smkapplication/x-smk
.sndaudio/basic.soltext/plain
.sortext/plain.spcapplication/x-pkcs7-certificates
.splapplication/futuresplash.spptext/xml
.ssmapplication/streamingmedia.sstapplication/vnd.ms-pki.certstore
.stlapplication/vnd.ms-pki.stl.stmtext/html
.styapplication/x-sty.svgtext/xml
.swfapplication/x-shockwave-flash.tdfapplication/x-tdf
.tg4application/x-tg4.tgaapplication/x-tga
.tifimage/tiff.tifapplication/x-tif
.tiffimage/tiff.tldtext/xml
.topdrawing/x-top.torrentapplication/x-bittorrent
.tsdtext/xml.txttext/plain
.uinapplication/x-icq.ulstext/iuls
.vcftext/x-vcard.vdaapplication/x-vda
.vdxapplication/vnd.visio.vmltext/xml
.vpgapplication/x-vpeg005.vsdapplication/vnd.visio
.vsdapplication/x-vsd.vssapplication/vnd.visio
.vstapplication/vnd.visio.vstapplication/x-vst
.vswapplication/vnd.visio.vsxapplication/vnd.visio
.vtxapplication/vnd.visio.vxmltext/xml
.wavaudio/wav.waxaudio/x-ms-wax
.wb1application/x-wb1.wb2application/x-wb2
.wb3application/x-wb3.wbmpimage/vnd.wap.wbmp
.wizapplication/msword.wk3application/x-wk3
.wk4application/x-wk4.wkqapplication/x-wkq
.wksapplication/x-wks.wmvideo/x-ms-wm
.wmaaudio/x-ms-wma.wmdapplication/x-ms-wmd
.wmfapplication/x-wmf.wmltext/vnd.wap.wml
.wmvvideo/x-ms-wmv.wmxvideo/x-ms-wmx
.wmzapplication/x-ms-wmz.wp6application/x-wp6
.wpdapplication/x-wpd.wpgapplication/x-wpg
.wplapplication/vnd.ms-wpl.wq1application/x-wq1
.wr1application/x-wr1.wriapplication/x-wri
.wrkapplication/x-wrk.wsapplication/x-ws
.ws2application/x-ws.wsctext/scriptlet
.wsdltext/xml.wvxvideo/x-ms-wvx
.xdpapplication/vnd.adobe.xdp.xdrtext/xml
.xfdapplication/vnd.adobe.xfd.xfdfapplication/vnd.adobe.xfdf
.xhtmltext/html.xlsapplication/vnd.ms-excel
.xlsapplication/x-xls.xlwapplication/x-xlw
.xmltext/xml.xplaudio/scpls
.xqtext/xml.xqltext/xml
.xquerytext/xml.xsdtext/xml
.xsltext/xml.xslttext/xml
.xwdapplication/x-xwd.x_bapplication/x-x_b
.sisapplication/vnd.symbian.install.sisxapplication/vnd.symbian.install
.x_tapplication/x-x_t.ipaapplication/vnd.iphone
.apkapplication/vnd.android.package-archive.xapapplication/x-silverlight-app

        当Content-Type是一些文件类型时,使用Content-Disposition可以指定浏览器下载文件时的默认文件名
        因此,我们想要使用gin实现下载文件的功能,只需要在接口返回时设置Response-Header中的Content-Type为文件类型,并设置Content-Disposition指定默认的文件名,然后将文件数据返回浏览器即可,具体代码如下:

func DownloadFileControl(c *gin.Context) {
	//  查询一些必要的参数 进行一些必要的验证
	attchIdStr := c.Query("attachment_id")
	attachmentName = c.Query("attachment_name")
	
	// 获取要返回的文件数据流
	// 看你文件存在哪里了,本地就直接os.Open就可以了,总之是要获取一个[]byte
	/*	fileContent, err := oss.GetOssClient().DownloadFile(req.AttachmentId, req.AttachmentName)
	if err != nil {
		logrus.Errorf("[DownloadFile] download file error,file_id = %d,file_name = %s,user_is = %d,err_msg= %s", req.UserId, req.AttachmentId, req.AttachmentName, err.Error())
		c.JSON(http.StatusOK, gin.H{
			"success": false,
			"msg":     "下载文件失败,请联系管理员",
		})
		return
	}*/
	
// 设置返回头并返回数据
	fileContentDisposition := "attachment;filename=\"" + attachmentName + "\""
	c.Header("Content-Type", "application/zip") // 这里是压缩文件类型 .zip
	c.Header("Content-Disposition", fileContentDisposition)
	c.Data(http.StatusOK, contentType, fileContent)

上述就是小编为大家分享的Golang Gin框架实现文件下载功能的示例代码怎么写了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI