文件存储系统有一个必不可少的功能就是文件下载功能,它应该支持各种格式的文件。本项目中,客户端使用vue3、axios和vuex,服务端使用Gin框架。下面介绍文件下载部分的代码和主要步骤。1、Gin框架部分:调用前两个函数,根据参数查找files表和user_files表中是否有文件记录。如果文件不存在,则返回404。如果存在,则执行以下操作。第二部分是Header的配置。这里我们重点关注三个配置信息。c.Header("Access-Control-Expose-Headers","Content-Disposition"):Content-Disposition配置文件名信息,文件名可以通过Content-Disposition传给客户端,客户端取出文件名作为下载文件的名称。但是这个项目默认是不公开的。如果c.Header("Access-Control-Expose-Headers","Content-Disposition")没有设置,content-type将不会暴露,客户端将无法接收。item配置的作用是暴露item,必须配置。c.Header("response-type","blob"):如果客户端以文件流的形式下载文件,服务端必须配置此项,否则下载的文件会报如下错误:文件格式为不正确或已经损坏。c.File(fm.FileAddress):参数为文件的存放地址,也是必填项,否则下载的文件为空。请求的post和get方法都可用。//DownloadHandler文件下载接口funcDownloadHandler(c*gin.Context){fileSha1:=c.Request.FormValue("file_sha1")userId,_:=strconv.ParseInt(c.Request.FormValue("user_id"),10,64)userFile,err:=se.FindUserFileByUserAndSha1(c,userId,fileSha1)iferr!=nil{fmt.Printf("找不到文件,错误是%s\n",err.Error())c.JSON(http.StatusNotFound,gin.H{"code":0,"msg":"Filenotfound","data":nil,})return}fm,err:=se.FindFileMetaByFileSha1(c,fileSha1)如果err!=nil{fmt.Printf("找不到文件,err是%s\n",err.Error())c.JSON(http.StatusNotFound,gin.H{"code":0,"msg":"Filenotfound","data":nil,})return}c.Header("Content-Type","application/octet-stream")//强制浏览器下载c.Header("Content-Disposition","attachment;filename=\""+userFile.FileName+"\"")//浏览器下载或预览c.Header("Content-Disposition","inline;filename=\""+userFile.FileName+"\"")c.Header("Content-Transfer-Encoding","binary")c.Header("Cache-Control","no-cache")c.Header("Access-Control-Expose-Headers","Content-Disposition")c.Header("response-type","blob")//以a形式下载时必须设置此项stream,否则前端下载的文件会出现格式不正确或损坏的问题c.File(fm.FileAddress)}2.Vue配置Vue使用的是版本3,因为下载文件的图标和下面的文件列表文件夹不在同一个vue文件中,需要传递全局变量,所以用vuex管理变量的状态很方便import{createStore}from"vuex";exportdefaultcreateStore({//variablestate:{downloadFileSha1:"",radioId:0,},mutations:{//修改下载文件的sha1EditDownloadFileSha1(state,param){state.downloadFileSha1=param},//修改radioId的值EditRadioId(state,value){state.radioId=value;}},actions:{//修改下载文件的sha1editDownloadFileSha1(context,payload){context.commit("EditDownloadFileSha1",payload);},//修改radioId的值editRadioId(context,payload){context.commit("EditRadioId",payload);}},modules:{},})文件列表页面选择一个下载文件,修改全局变量downloadFileSha1和radioId
