Go Gin 實現(xiàn)文件的上傳下載流讀取
文件上傳
router
router.POST("/resources/common/upload", service.UploadResource)
service
type: POST
data:{
“saveDir”:“保存的路徑”,
“fileName”:“文件名稱不帶后綴”
}
// 上傳文件
func UploadResource(c *gin.Context) {
saveDirParam := c.PostForm("saveDir") // 文件目錄
fileNameParam := c.PostForm("fileName") // 文件名稱
//目錄
var saveDir = ""
//名稱
var saveName = ""
//完整路徑
var savePath = ""
//獲取文件
file, header, errFile := c.Request.FormFile("file")
//處理獲取文件錯誤
if errFile != nil || common.IsEmpty(header.Filename) {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": "請選擇文件",
"dir": saveDir,
"name": saveName,
"path": savePath,
})
return
}
//目錄請求參數(shù)為空
if common.IsEmpty(saveDirParam) {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": "請求參數(shù)錯誤!",
"dir": saveDir,
"name": saveName,
"path": savePath,
})
return
}
//如果上傳的名稱為空,則自動生成名稱
if common.IsEmpty(fileNameParam) {
fileNameParam = GenerateResourceNo()
}
//獲取上傳文件的后綴(類型)
uploadFileNameWithSuffix := path.Base(header.Filename)
uploadFileType := path.Ext(uploadFileNameWithSuffix)
//文件保存目錄
saveDir = "/attachment" + saveDirParam
//保存的文件名稱
saveName = fileNameParam + uploadFileType
savePath = saveDir + "/" + saveName
//打開目錄
localFileInfo, fileStatErr := os.Stat(saveDir)
//目錄不存在
if fileStatErr != nil || !localFileInfo.IsDir() {
//創(chuàng)建目錄
errByMkdirAllDir := os.MkdirAll(saveDir, 0755)
if errByMkdirAllDir != nil {
logs.Error("%s mkdir error.....", saveDir, errByMkdirAllDir.Error())
c.JSON(http.StatusOK, gin.H{
"success": false,
"dir": saveDir,
"name": saveName,
"path": savePath,
"message": "創(chuàng)建目錄失敗",
})
return
}
}
////上傳文件前 先刪除該資源之前上傳過的資源文件
////(編輯-重新選擇文件-需要先刪除該資源之前上傳過的資源文件)
////該代碼執(zhí)行的條件----上傳的名稱是唯一的,否則會出現(xiàn)誤刪
////獲取文件的前綴
//fileNameOnly := fileNameParam
//deleteFileWithName(fileNameOnly, saveDir)
//deleteFileWithName(fileNameOnly, model.WebConfig.ResourcePath+"/"+
// model.WebConfig.WebConvertToPath)
out, err := os.Create(savePath)
if err != nil {
logs.Error(err)
}
defer out.Close()
_, err = io.Copy(out, file)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"dir": saveDir,
"name": saveName,
"path": savePath,
"message": err.Error(),
})
return
}
//沒有錯誤的情況下
c.JSON(http.StatusOK, gin.H{
"success": true,
"dir": saveDir,
"name": saveName,
"path": savePath,
"message": "上傳成功",
})
return
}
js提交例子:
注:需導(dǎo)入jquery.js 和 ajaxfileupload.js
//上傳文件
$.ajaxFileUpload(
{
url: '/resources/common/upload', //用于文件上傳的服務(wù)器端請求地址
secureuri: false, //是否需要安全協(xié)議,一般設(shè)置為false
fileElementId: fileUploadDomId, //文件上傳域的ID
data: {
"saveDir":fileSaveDir,
"fileName":fileSaveName
},
dataType: 'json', //返回值類型 一般設(shè)置為json
contentType:'application/json',//提交的數(shù)據(jù)類型
async: false,
success: function (data, status) //服務(wù)器成功響應(yīng)處理函數(shù)
{
if (data.success){
fileSaveName=fileSaveDir+"/"+data.name;
console.log("上傳成功,返回的文件的路徑:",fileSaveName)
}else{
console.log("上傳失敗,返回的文件的路徑:",fileSaveName)
return
}
},
error: function (data, status, e)//服務(wù)器響應(yīng)失敗處理函數(shù)
{
console.log("e==",e);
return
}
}
);
文件的下載
router
Type:‘GET'
普通鏈接格式非restful風(fēng)格
參數(shù)url:下載的文件的路徑
- Jquery解碼:decodeURIComponent(url);
- Jquery編碼:encodeURIComponent(url);
例:http://127.0.0.0.1:8080//pub/common/download?url=“/attachment/demo.docx”
router.GET("/pub/common/download", service.PubResFileStreamGetService)
service
//下載次數(shù)
func UserFileDownloadCommonService(c *gin.Context) {
filePath := c.Query("url")
//打開文件
fileTmp, errByOpenFile := os.Open(filePath)
defer fileTmp.Close()
//獲取文件的名稱
fileName:=path.Base(filePath)
if common.IsEmpty(filePath) || common.IsEmpty(fileName) || errByOpenFile != nil {
logs.Error("獲取文件失敗")
c.Redirect(http.StatusFound, "/404")
return
}
c.Header("Content-Type", "application/octet-stream")
//強制瀏覽器下載
c.Header("Content-Disposition", "attachment; filename="+fileName)
//瀏覽器下載或預(yù)覽
c.Header("Content-Disposition", "inline;filename="+fileName)
c.Header("Content-Transfer-Encoding", "binary")
c.Header("Cache-Control", "no-cache")
c.File(filePath)
return
}
文件流讀取
router
Type:‘GET'
普通鏈接格式非restful風(fēng)格
參數(shù)url:下載的文件的路徑
- Jquery解碼:decodeURIComponent(url);
- Jquery編碼:encodeURIComponent(url);
例:http://127.0.0.0.1:8080//pub/common/file_stream?url=“/attachment/demo.docx”
router.GET("/pub/common/file_stream", service.PubResFileStreamGetService)
service
//map for Http Content-Type Http 文件類型對應(yīng)的content-Type
var HttpContentType = map[string]string{
".avi": "video/avi",
".mp3": " audio/mp3",
".mp4": "video/mp4",
".wmv": " video/x-ms-wmv",
".asf": "video/x-ms-asf",
".rm": "application/vnd.rn-realmedia",
".rmvb": "application/vnd.rn-realmedia-vbr",
".mov": "video/quicktime",
".m4v": "video/mp4",
".flv": "video/x-flv",
".jpg": "image/jpeg",
".png": "image/png",
}
//根據(jù)文件路徑讀取返回流文件 參數(shù)url
func PubResFileStreamGetService(c *gin.Context) {
filePath := c.Query("url")
//獲取文件名稱帶后綴
fileNameWithSuffix := path.Base(filePath)
//獲取文件的后綴
fileType := path.Ext(fileNameWithSuffix)
//獲取文件類型對應(yīng)的http ContentType 類型
fileContentType := HttpContentType[fileType]
if common.IsEmpty(fileContentType) {
c.String(http.StatusNotFound, "file http contentType not found")
return
}
c.Header("Content-Type", fileContentType)
c.File(filePath)
}
到此這篇關(guān)于Go Gin實現(xiàn)文件上傳下載的示例代碼的文章就介紹到這了,更多相關(guān)Go Gin 文件上傳下載內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- 用go gin server來做文件上傳服務(wù)