Example #1
0
        /// <summary>
        /// 本地文件上传,秒传(根据lin_file表中的md5,与当前文件的路径是否在本地),如果不在,重新上传,覆盖文件表记录
        /// </summary>
        /// <param name="file"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task <FileDto> UploadAsync(IFormFile file, string type, int key = 0)
        {
            string     md5      = HashUtil.GetHash <MD5>(file.OpenReadStream());
            FileEntity fileInfo = await _fileRepo.Where(r => r.Md5 == md5 && r.Type == 1).OrderByDescending(r => r.CreateTime).FirstAsync();

            if (fileInfo != null && File.Exists(Path.Combine(_hostingEnv.WebRootPath, fileInfo.Path)))//如果文件存在,则直接返回文件信息
            {
                return(new FileDto
                {
                    Id = fileInfo.Id,
                    Key = "file_" + key,
                    Path = fileInfo.Path,
                    Url = Appsettings.FileStorage.LocalFileHost + fileInfo.Path
                });
            }

            long id;

            var(path, len) = await this.LocalUploadAsync(file, type);

            if (fileInfo == null)
            {
                FileEntity saveLinFile = new FileEntity()
                {
                    Extension = Path.GetExtension(file.FileName),
                    Md5       = md5,
                    Name      = file.FileName,
                    Path      = path,
                    Type      = 1,
                    Size      = len
                };
                id = (await _fileRepo.InsertAsync(saveLinFile)).Id;//插入文件数据
            }
            else
            {
                await _fileRepo.UpdateDiy.Where(a => a.Id == fileInfo.Id).Set(a => a.Path, path).ExecuteAffrowsAsync();//仅更新路径字段

                id = fileInfo.Id;
            }

            return(new FileDto
            {
                Id = id,
                Key = "file_" + key,
                Path = path,
                Url = Appsettings.FileStorage.LocalFileHost + path
            });
        }