Ejemplo n.º 1
0
        public IActionResult SaveChunkFile()
        {
            var result = new ResultAdaptDto();
            //uploadfile,uploadvideo
            string action    = RequestHelper.GetPostString("action");
            string guid      = RequestHelper.GetPostString("guid");
            string fileName  = RequestHelper.GetPostString("name");
            string chunk     = RequestHelper.GetPostString("chunk");
            var    tempDir   = GlobalContext.WebRootPath + "/UploadTemp/" + guid;                                  // 缓存文件夹
            var    targetDir = GlobalContext.WebRootPath + "/upfiles/videos/" + DateTime.Now.ToString("yyyyMMdd"); // 目标文件夹

            if (action == "uploadfile")
            {
                targetDir = GlobalContext.WebRootPath + "/upfiles/attachments/" + DateTime.Now.ToString("yyyyMMdd"); // 目标文件夹
            }
            if (!System.IO.Directory.Exists(targetDir))
            {
                System.IO.Directory.CreateDirectory(targetDir);
            }


            var file = Request.Form.Files[0];

            int    index   = fileName.LastIndexOf('.');
            string extName = fileName.Substring(index);

            //单文件小于分片大小的直接保存下来
            if (file.Length < THUNK_SIZE)
            {
                //判断是否是单文件
                if (!FileChunkCache.ExistChunk(guid))
                {
                    string guidFileName = $"{IdHelper.ObjectId()}{extName}";
                    //这个hostingEnv.WebRootPath就是要存的地址可以改下
                    string newfilename = Path.Combine(targetDir, guidFileName);

                    using (FileStream fs = System.IO.File.Create(newfilename))
                    {
                        file.CopyTo(fs);
                        fs.Flush();
                    }
                    string returnPath = "/upfiles/videos/" + DateTime.Now.ToString("yyyyMMdd") + "/" + guidFileName;
                    if (action == "uploadfile")
                    {
                        returnPath = "/upfiles/attachments/" + DateTime.Now.ToString("yyyyMMdd") + "/" + guidFileName;
                    }
                    result.status     = true;
                    result.statusCode = 200;
                    result.data.Add("url", returnPath);
                    result.data.Add("fileName", fileName);
                    return(Content(result.ToJson()));
                }
            }

            //添加分片id缓存
            FileChunkCache.AddChunkId(guid);
            //大于分片大小的直接保存下来
            if (!System.IO.Directory.Exists(tempDir))
            {
                System.IO.Directory.CreateDirectory(tempDir);
            }
            string filePath = tempDir + "/" + chunk.ToString() + extName;

            //file.SaveFile(filePath);
            using (FileStream fs = System.IO.File.Create(filePath))
            {
                file.CopyTo(fs);
                fs.Flush();
            }

            return(Content(result.ToJson()));
        }