.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
#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