public FileStreamResult DownLoad([FromServices] IWebHostEnvironment environment, string FileID) { //try //{ var userSession = _tokenManager.GetSessionInfo(); if (string.IsNullOrEmpty(FileID)) { throw new Exception("文件ID不允许为空"); } gnl_File file = _gnlfileService.GetId(FileID); if (file == null) { throw new Exception("文件不存在"); } string filepath = file.AbsoluteFilePath; var stream = System.IO.File.OpenRead(filepath); string fileExt = file.FileExt; // 这里可以写一个获取文件扩展名的方法,获取扩展名 //获取文件的ContentType var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider(); var memi = provider.Mappings[fileExt]; var fileName = System.IO.Path.GetFileNameWithoutExtension(file.FileName); _gnlfileService.Update(f => f.FileID.ToString() == FileID, f => new gnl_File { DownloadCount = file.DownloadCount + 1 }); return(File(stream, memi, fileName)); //} //catch(Exception ex) //{ //return toResponse(StatusCodeType.Error, ex.Message); //} }
public static string allowtype = AppSettings.Configuration["FileSettiong:AllowType"]; //上传文件类型 /// <summary> /// 保存文件至设置路径 /// </summary> /// <param name="WebRootPath">接口服务所在路径</param> /// <param name="file">文件流</param> /// <param name="FileName">文件名称</param> /// <param name="FileGroup">文件分类</param> /// <returns></returns> public static gnl_File CreateFile(string WebRootPath, IFormFile file, string FileName, string FileType = "Attach") { try { gnl_File gnlfile = new gnl_File(); if (filerootpath == "") { filerootpath = WebRootPath; } Guid fileid = Guid.NewGuid(); string flodpath = Path.Combine(FileType, DateTime.Now.ToString("yyyyMM")); string folderpath = Path.Combine(filerootpath, flodpath); string ext = Path.GetExtension(FileName); if (!Directory.Exists(folderpath)) { Directory.CreateDirectory(folderpath); } string path = Path.Combine(folderpath, fileid.ToString()); using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { file.CopyTo(stream); } gnlfile.FileID = fileid.ToString().ToUpper(); //文件id gnlfile.FileName = FileName; //文件名 gnlfile.FileExt = ext; //文件后缀名 gnlfile.FileRootPath = filerootpath; //存放路径 gnlfile.AbsoluteFilePath = path; //绝对路径 gnlfile.RelativeFilePath = Path.Combine(flodpath, fileid.ToString()); //相对路径 gnlfile.FileSize = (int)file.Length; //文件大小 gnlfile.FileType = FileType; return(gnlfile); } catch (Exception ex) { return(null); } }