Go實現文件分片上傳
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 }
以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。
推薦閱讀:
- GO實現文件上傳操作
- Golang實現http文件上傳小功能的案例
- 解決el-upload批量上傳隻執行一次成功回調on-success的問題
- Vue+Element UI 實現視頻上傳功能
- Jmeter並發執行Python 腳本的完整流程