.Net Core Web API 上传下载 压缩存储
#region 文件上传 /// <summary> /// 文件上传 /// </summary> /// <param name="file">文件上传内容</param> /// <returns></returns> [HttpPost] public async Task<string> UploaderFiles([Required] IFormFile file) { if (file.Length == 0) { throw new Exception("上传文件不能为空"); } if (file.Length > 1024 * 1024 * 500) { throw new Exception("上传文件不能大于500M"); } string fileName =file.FileName; Stream stream = file.OpenReadStream(); byte[] buffer = new byte[stream.Length]; await stream.ReadAsync(buffer, 0, buffer.Length); stream.Close(); string fileClass = buffer[0].ToString() + buffer[1].ToString(); string FilePath = Guid.NewGuid().ToString() + "\\" + FileName; string RootPath = Path.Combine(Tools.FilePath(), FilePath); string DirecotryPath = Path.GetDirectoryName(RootPath); if (!Directory.Exists(DirecotryPath)) { Directory.CreateDirectory(DirecotryPath); } byte[] res; try { using MemoryStream ms = new MemoryStream(); using ZipArchive zip = new ZipArchive(ms, ZipArchiveMode.Create, true); //通过aws下载文件流 ZipArchiveEntry entry = zip.CreateEntry(FileName);//压缩文件内创建一个文件,流是什么文件格式就用什么格式 using Stream sw = entry.Open(); await sw.WriteAsync(buffer, 0, buffer.Length);//将文件的字节写到文件中 InvokeWriteFile(zip);//重新计算压缩文件的大小,此处参考别人的 int nowPos = (int)ms.Position; res = new byte[ms.Length]; ms.Position = 0; await ms.ReadAsync(res, 0, res.Length); ms.Position = nowPos; } catch (Exception ex) { throw new Exception("上传文件失败"); } await File.WriteAllBytesAsync(RootPath + ".zip", res); return FilePath; } #endregion
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | #region 下载文件 /// <summary> /// 下载文件 /// </summary> /// <param name="filePath">文件地址</param> /// <returns></returns> [HttpGet] public async Task<FileStreamResult> DownLoadFiles( string filePath) { if ( string .IsNullOrWhiteSpace(filePath)) { throw new Exception( "文件地址不能为空" ); } string FilePath = Path.Combine(Tools.FilePath(), filePath); string zipFilePath = FilePath + ".zip" ; if (!File.Exists(zipFilePath)) { throw new Exception( "文件未找到" ); } List< byte > bytes = new List< byte >(); using ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)); ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null ) { int size = 2048; byte [] data = new byte [2048]; while ( true ) { size = await s.ReadAsync(data, 0, data.Length); if (size > 0) { bytes.AddRange(data); } else { break ; } } } MemoryStream memoryStream = new MemoryStream(bytes.ToArray()); return File(memoryStream , "application/octet-stream;charset=UTF-8" , new FileInfo(filePath).Name); } #endregion |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!