亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Golang?Gin框架實現文件下載功能的示例代碼怎么寫

發布時間:2021-12-09 15:07:53 來源:億速云 閱讀:423 作者:柒染 欄目:開發技術

這期內容當中小編將會給大家帶來有關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

陇南市| 巴林左旗| 平塘县| 渝北区| 达州市| 盐源县| 孝昌县| 鲁山县| 保亭| 汉阴县| 靖安县| 闻喜县| 越西县| 永安市| 丰原市| 高淳县| 富平县| 营口市| 宜城市| 犍为县| 银川市| 怀来县| 顺昌县| 民权县| 新乡县| 九江县| 秭归县| 峡江县| 神池县| 棋牌| 朔州市| 双鸭山市| 卫辉市| 内黄县| 新巴尔虎右旗| 罗源县| 昆山市| 乐都县| 定南县| 化隆| 明溪县|