網站首頁 編程語言 正文
Go語言在寫HTTP服務程序時,會經常用到文件上傳和文件下載,文件上傳和文件下載都可以用http包,默認的功能基本上夠用了。http包支持文件下載的斷點續傳和進度顯示,文件上傳貌似不支持斷點續傳,不知道是不是要web端來實現。
然后我自己配合web端實現了大文件分片上傳,來完成斷點續傳和進度顯示的功能。
基本思想是,在web端將上傳的文件進行分片處理,然后向服務端發送上傳請求(UploadRequest)包括文件名,MD5,文件大小,和文件總片數。
然后開始一片一片的上傳(Upload)。如果暫停了或者斷網失敗了,就記錄當前上傳片的片數,下一次上傳,重發UploadRequest,chunkPos為續傳位置片數,然后從這個記錄的片數開始接著上傳(Upload)。在服務端,記錄首次請求的文件名,MD5,文件大小,文件總片數,然后開始接收每一片,將每一個片保存為一個單獨的文件,在接收完最后一個片時,將所有的分片份文件進行合并。保存為對應的文件名。最后再校驗MD5碼。
對于不同用戶的請求,將文件上傳的信息存儲到session中,當前文件上傳暫停后,上傳其它文件時,向session增加新文件的信息。暫停后,接著上傳最開始的文件,則直接從session中取得該文件的信息,包括文件名,上傳到某一個片的信息等。
服務端實現代碼:
func UploadRequest(w http.ResponseWriter, r *http.Request) { ?? ?log.WithFields(log.Fields{ ?? ??? ?"HTTP": r.Method, ?? ??? ?"FUNC": "UploadRequest", ?? ?}).Info("HTTP REQUEST") ?? ?header := w.Header() ?? ?header.Add("Content-Type", "application/json") ?? ?/* session authentication */ ?? ?sess := session.GlobalSessions.SessionCheck(w, r) ?? ?if sess == nil { ?? ??? ?log.Error("sess check error") ?? ??? ?fmt.Fprintf(w, config.FmtStr, "3000", "error", "session check error") ?? ??? ?return ?? ?} ?? ?defer r.Body.Close() ?? ?con, _ := ioutil.ReadAll(r.Body) //獲取post的body數據 ?? ?log.Info("UploadRequest json: ", string(con)) ?? ?var uploadReq uploadRequest ?? ?err := json.Unmarshal([]byte(con), &uploadReq) /* 解析json字符串數據到結構體中 */ ?? ?if err != nil { ?? ??? ?log.Error("json unmarshal error") ?? ??? ?fmt.Fprintf(w, config.FmtStr, "2000", "error", "json unmarshal error") ?? ??? ?return ?? ?} ?? ?switch uploadReq.Option { ?? ?case "reUploadFile": ?? ??? ?{ ?? ??? ??? ?sess.Set("currentFile", uploadReq) ?? ??? ??? ?err := os.Remove("./tmp/" + uploadReq.FileName + "/" + uploadReq.FileName + "_" + uploadReq.ChunkPos) ?? ??? ??? ?if err != nil { ?? ??? ??? ??? ?log.Error(err) ?? ??? ??? ?} ?? ??? ??? ?fmt.Fprintf(w, config.FmtStr, "1000", "success", "reupload request success") ?? ??? ?} ?? ?case "uploadFile": ?? ??? ?{ ?? ??? ??? ?err = os.Mkdir("./tmp/"+uploadReq.FileName, 0777) ?? ??? ??? ?if err != nil { ?? ??? ??? ??? ?log.Info(err) ?? ??? ??? ??? ?fmt.Fprintf(w, config.FmtStr, "3000", "error", "mkdir error") ?? ??? ??? ?} else { ?? ??? ??? ??? ?log.Infof("create dir %s ok\r\n", uploadReq.FileName) ?? ??? ??? ?} ?? ??? ??? ?// 文件上傳信息保存,保存到session中,用于分片續傳時使用 ?? ??? ??? ?sess.Set(uploadReq.FileName, uploadReq) ?? ??? ??? ?sess.Set("currentFile", uploadReq) ?? ??? ??? ?fmt.Fprintf(w, config.FmtStr, "1000", "success", "upload request success") ?? ??? ?} ?? ?case "uploadCancel": ?? ??? ?{ ?? ??? ??? ?err = os.RemoveAll("./tmp/" + uploadReq.FileName) ?? ??? ??? ?if err != nil { ?? ??? ??? ??? ?log.Fatal(err) ?? ??? ??? ?} ?? ??? ??? ?sess.Delete(uploadReq.FileName) ?? ??? ??? ?fmt.Fprintf(w, config.FmtStr, "1000", "success", "upload file success") ?? ??? ??? ?return ?? ??? ?} ?? ?default: ?? ??? ?{ ?? ??? ??? ?fmt.Fprintf(w, config.FmtStr, "2000", "error", "upload request option error") ?? ??? ?} ?? ?} } /* 分片上傳功能實現 */ func Upload(w http.ResponseWriter, r *http.Request) { ?? ?log.WithFields(log.Fields{ ?? ??? ?"HTTP": r.Method, ?? ??? ?"FUNC": "Upload", ?? ?}).Info("HTTP REQUEST") ?? ?header := w.Header() ?? ?header.Add("Content-Type", "application/json") ?? ?/* session authentication */ ?? ?sess := globalSessions.SessionCheck(w, r) //session 檢查的接口封裝 ?? ?if sess == nil { ?? ??? ?log.Error("session check failed") ?? ??? ?fmt.Fprintf(w, config.FmtStr, "3000", "error", "session check failed") ?? ??? ?return ?? ?} ?? ?current_dir := sess.Get("current_dir") ?? ?log.Info("current dir: ", current_dir) ?? ?up_dir := sess.Get("up_dir") ?? ?log.Info("up_dir: ", up_dir) ?? ?// var current_dir string = "./river/test" ?? ?/* 表單上傳文件 */ ?? ?if r.Method == "GET" { ?? ??? ?crutime := time.Now().Unix() ?? ??? ?h := md5.New() ?? ??? ?io.WriteString(h, strconv.FormatInt(crutime, 10)) ?? ??? ?token := fmt.Sprintf("%x", h.Sum(nil)) ?? ??? ?t, _ := template.ParseFiles("upload.gtpl") ?? ??? ?t.Execute(w, token) ?? ?} else { ?? ??? ?r.ParseMultipartForm(32 << 20) ?? ??? ?file, _, err := r.FormFile("uploadfile") ?? ??? ?if err != nil { ?? ??? ??? ?log.Error(err) ?? ??? ??? ?return ?? ??? ?} ?? ??? ?defer file.Close() ?? ??? ?var uploadFileInfo uploadRequest ?? ??? ?uploadFileInfo = sess.Get("currentFile").(uploadRequest) ?? ??? ?// fmt.Fprintf(w, "%v", sess.Get("fileName")) ?? ??? ?var fileName string = uploadFileInfo.FileName + "_" + uploadFileInfo.ChunkPos ?? ??? ?/* 判斷上傳的文件是否已經存在,可能發生同名的情況 */ ?? ??? ?log.Debug("fileName: ", fileName) ?? ??? ?_, err = os.Stat("./tmp/" + uploadFileInfo.FileName + "/" + fileName) ?? ??? ?var f *os.File ?? ??? ?if err == nil { ?? ??? ??? ?fmt.Fprintf(w, config.FmtStr, "3000", "error", "file is exsited") ?? ??? ??? ?return ?? ??? ?} else { ?? ??? ??? ?f, err = os.OpenFile("./tmp/"+uploadFileInfo.FileName+"/"+fileName, os.O_WRONLY|os.O_CREATE, 0666) // 此處假設當前目錄下已存在test目錄 ?? ??? ?} ?? ??? ?defer f.Close() ?? ??? ?if err != nil { ?? ??? ??? ?log.Error(err) ?? ??? ??? ?fmt.Fprintf(w, config.FmtStr, "3000", "error", "create file error") ?? ??? ??? ?return ?? ??? ?} ?? ??? ?io.Copy(f, file) //這里進行大文件copy會導致內存占用過大。一段時候后會進行GC回收 ?? ??? ?log.Info("copy ok") ?? ??? ?// 判斷是否單個文件是否上傳完畢,上傳完畢則合并文件到目標文件夾 ?? ??? ?if uploadFileInfo.ChunkPos == uploadFileInfo.ChunkNum { ?? ??? ??? ?f.Close() ?? ??? ??? ?_, err = os.Stat(current_dir.(string) + uploadFileInfo.FileName) ?? ??? ??? ?var fii *os.File ?? ??? ??? ?if err == nil { ?? ??? ??? ??? ?// 如果已經存在這個文件了,則在當前文件名后增加日期 ?? ??? ??? ??? ?time := time.Now().Format("2006-01-02_15-04-05") ?? ??? ??? ??? ?log.Debug("Time: ", time) ?? ??? ??? ??? ?var fileName []byte = []byte(current_dir.(string) + uploadFileInfo.FileName) ?? ??? ??? ??? ?var fileNameFinal []byte = fileName ?? ??? ??? ??? ?log.Debug("file_name: ", string(fileName)) ?? ??? ??? ??? ?var preFileName []byte ?? ??? ??? ??? ?var sufFileName []byte ?? ??? ??? ??? ?for i := len(fileName) - 1; i > 0; i-- { ?? ??? ??? ??? ??? ?if fileName[i] == '.' { ?? ??? ??? ??? ??? ??? ?preFileName = fileName[:i] // 文件名前綴 test ?? ??? ??? ??? ??? ??? ?sufFileName = fileName[i:] // 文件名后綴 .txt ?? ??? ??? ??? ??? ??? ?fileNameFinal = []byte(string(preFileName) + "_" + time + string(sufFileName)) ?? ??? ??? ??? ??? ??? ?log.Info("fileNameFile: ", fileNameFinal) ?? ??? ??? ??? ??? ??? ?break ?? ??? ??? ??? ??? ?} ?? ??? ??? ??? ?} ?? ??? ??? ??? ?fii, err = os.OpenFile(string(fileNameFinal), os.O_WRONLY|os.O_CREATE, 0777) // 此處假設當前目錄下已存在test目錄 ?? ??? ??? ?} else { ?? ??? ??? ??? ?fii, err = os.OpenFile(current_dir.(string)+uploadFileInfo.FileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, os.ModePerm) ?? ??? ??? ?} ?? ??? ??? ?defer fii.Close() ?? ??? ??? ?if err != nil { ?? ??? ??? ??? ?log.Error(err) ?? ??? ??? ??? ?fmt.Fprintf(w, config.FmtStr, "3000", "error", "Open object file error") ?? ??? ??? ??? ?return ?? ??? ??? ?} ?? ??? ??? ?index, _ := strconv.Atoi(uploadFileInfo.ChunkNum) ?? ??? ??? ?for i := 1; i <= index; i++ { ?? ??? ??? ??? ?f11, err := os.OpenFile("./tmp/"+uploadFileInfo.FileName+"/"+uploadFileInfo.FileName+"_"+strconv.Itoa(int(i)), os.O_RDONLY, os.ModePerm) ?? ??? ??? ??? ?if err != nil { ?? ??? ??? ??? ??? ?log.Error(err) ?? ??? ??? ??? ??? ?fmt.Fprintf(w, config.FmtStr, "3000", "error", "Open slice file error") ?? ??? ??? ??? ??? ?return ?? ??? ??? ??? ?} ?? ??? ??? ??? ?b, err := ioutil.ReadAll(f11) ?? ??? ??? ??? ?if err != nil { ?? ??? ??? ??? ??? ?log.Error(err) ?? ??? ??? ??? ??? ?fmt.Fprintf(w, config.FmtStr, "3000", "error", "ioutil readall error") ?? ??? ??? ??? ??? ?return ?? ??? ??? ??? ?} ?? ??? ??? ??? ?fii.Write(b) ?? ??? ??? ??? ?f11.Close() ?? ??? ??? ?} ?? ??? ??? ?err = os.RemoveAll("./tmp/" + uploadFileInfo.FileName) ?? ??? ??? ?if err != nil { ?? ??? ??? ??? ?log.Error(err) ?? ??? ??? ?} ?? ??? ??? ?sess.Delete(uploadFileInfo.FileName) ?? ??? ??? ?fii.Close() ?? ??? ??? ?if uploadFileInfo.MD5 == FileMD5(fii.Name()) { ?? ??? ??? ??? ?err := os.Remove(current_dir.(string) + fii.Name()) ?? ??? ??? ??? ?if err != nil { ?? ??? ??? ??? ??? ?log.Error(err) ?? ??? ??? ??? ?} ?? ??? ??? ??? ?fmt.Fprintf(w, config.FmtStr, "3000", "error", "upload file md5 error") ?? ??? ??? ?} else { ?? ??? ??? ??? ?fmt.Fprintf(w, config.FmtStr, "1000", "success", "upload one file all slice success") ?? ??? ??? ?} ?? ??? ??? ?return ?? ??? ?} ?? ??? ?chunkPos, err := strconv.Atoi(uploadFileInfo.ChunkPos) ?? ??? ?if err != nil { ?? ??? ??? ?log.Error(err) ?? ??? ?} ?? ??? ?uploadFileInfo.ChunkPos = strconv.Itoa(chunkPos + 1) ?? ??? ?sess.Set(uploadFileInfo.FileName, uploadFileInfo) ?? ??? ?sess.Set("currentFile", uploadFileInfo) ?? ??? ?fmt.Fprintf(w, config.FmtStr, "1000", "success", "upload file success") ?? ?} } func FileMD5(file string) string { ?? ?f, err := os.Open(file) ?? ?defer f.Close() ?? ?if err != nil { ?? ??? ?log.Info(err) ?? ??? ?return "" ?? ?}?? ?buffer, _ := ioutil.ReadAll(f) ?? ?data := buffer ?? ?has := md5.Sum(data) ?? ?md5str := fmt.Sprintf("%x", has) ?? ?return md5str }
原文鏈接:https://blog.csdn.net/duapple/article/details/109739491
相關推薦
- 2022-08-10 pandas.DataFrame.from_dict直接從字典構建DataFrame的方法_pyth
- 2022-08-20 Python超詳細講解元類的使用_python
- 2022-09-27 使用Python?matplotlib繪制簡單的柱形圖、折線圖和直線圖_python
- 2022-03-23 Android應用內懸浮窗Activity的簡單實現_Android
- 2023-05-18 Python使用requirements.txt和pip打包批量安裝的實現_python
- 2022-11-21 Redis不同數據類型的命令語句詳解_Redis
- 2022-10-22 Python?NumPy教程之數組的創建詳解_python
- 2022-06-12 C語言超詳細講解棧的實現及代碼_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支