您好,登錄后才能下訂單哦!
這篇文章主要講解了“怎么使用Go實現(xiàn)文件分片上傳”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“怎么使用Go實現(xiàn)文件分片上傳”吧!
基本思想是,在web端將上傳的文件進行分片處理,然后向服務端發(fā)送上傳請求(UploadRequest)包括文件名,MD5,文件大小,和文件總片數(shù)。
然后開始一片一片的上傳(Upload)。如果暫停了或者斷網(wǎng)失敗了,就記錄當前上傳片的片數(shù),下一次上傳,重發(fā)UploadRequest,chunkPos為續(xù)傳位置片數(shù),然后從這個記錄的片數(shù)開始接著上傳(Upload)。在服務端,記錄首次請求的文件名,MD5,文件大小,文件總片數(shù),然后開始接收每一片,將每一個片保存為一個單獨的文件,在接收完最后一個片時,將所有的分片份文件進行合并。保存為對應的文件名。最后再校驗MD5碼。
對于不同用戶的請求,將文件上傳的信息存儲到session中,當前文件上傳暫停后,上傳其它文件時,向session增加新文件的信息。暫停后,接著上傳最開始的文件,則直接從session中取得該文件的信息,包括文件名,上傳到某一個片的信息等。
服務端實現(xiàn)代碼:
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數(shù)據(jù) log.Info("UploadRequest json: ", string(con)) var uploadReq uploadRequest err := json.Unmarshal([]byte(con), &uploadReq) /* 解析json字符串數(shù)據(jù)到結構體中 */ 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中,用于分片續(xù)傳時使用 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") } } } /* 分片上傳功能實現(xiàn) */ 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 /* 判斷上傳的文件是否已經(jīng)存在,可能發(fā)生同名的情況 */ 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 { // 如果已經(jīng)存在這個文件了,則在當前文件名后增加日期 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 }
感謝各位的閱讀,以上就是“怎么使用Go實現(xiàn)文件分片上傳”的內容了,經(jīng)過本文的學習后,相信大家對怎么使用Go實現(xiàn)文件分片上傳這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。