golang上传当处理大文件上传时,分块上传和流式上传
golang上传当处理大文件上传时,分块上传和流式上传
type Uploads struct { } type ReturnPdf struct { Url string `json:"url"` Img string `json:"img"` Name string `json:"name"` } func (e Uploads ) ChunkUpload(c *gin.Context) (returnPdf storage.ReturnPdf, err error) { // 获取文件信息 file, header, err := c.Request.FormFile("file") if err != nil { return returnPdf, err } defer file.Close() rootDir := configs.ApplicationConfig.ImgUri fileDir := fmt.Sprintf("/uploads/images/%s/", time.Now().Format("200601")) _, err = os.Stat(rootDir + fileDir) if err != nil { if !os.IsExist(err) { // 目录不存在,创建目录 err = os.MkdirAll(rootDir+fileDir, os.ModePerm) if err != nil { fmt.Println(err) return returnPdf, err } } } //文件重命名 fileName := strconv.FormatInt(time.Now().Unix(), 10) + strconv.Itoa(rand.Intn(999999-100000)+100000) + path.Ext(header.Filename) filePath := rootDir + fileDir // 创建保存路径 savePath := filepath.Join(filePath, fileName) out, err := os.Create(savePath) if err != nil { return returnPdf, err } defer out.Close() // 分块上传 buffer := make([]byte, 1024*1024) // 1MB 缓冲区 for { n, err := file.Read(buffer) if err != nil && err != io.EOF { return returnPdf, err } if n == 0 { break } _, err = out.Write(buffer[:n]) if err != nil { return returnPdf, err } } returnPdf.Url=fileDir + fileName returnPdf.Name=fileName returnPdf.Path=savePath return returnPdf ,nil }