Files
Web_PMSApi_Server_V1_Prod/WebApplication2/Controllers/ValuesController.cs
2025-12-11 14:13:27 +08:00

89 lines
3.1 KiB
C#

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using System.IO.Compression;
namespace WebApplication2.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class ValuesController : ControllerBase
{
public IWebHostEnvironment _environment;
private readonly IContentTypeProvider _contentTypeProvider;
public ValuesController(IWebHostEnvironment e)
{
this._environment = e;
_contentTypeProvider = new FileExtensionContentTypeProvider();
}
[HttpGet()]
public async Task<IActionResult> DownloadImage(string imageName)
{
try
{
// 安全检查:防止路径遍历攻击
if (imageName.Contains("..") || imageName.Contains("/") || imageName.Contains("\\"))
{
return BadRequest("无效的文件名");
}
// 构建完整文件路径
var imagePath = Path.Combine(_environment.ContentRootPath, "images", imageName);
// 检查文件是否存在
if (!System.IO.File.Exists(imagePath))
{
return NotFound("图片不存在");
}
// 获取文件内容类型
if (!_contentTypeProvider.TryGetContentType(imageName, out var contentType))
{
contentType = "application/octet-stream";
}
// 读取文件并返回
//var fileBytes = await System.IO.File.ReadAllBytesAsync(imagePath);
var validFiles = new List<(string FileName, string FilePath)>();
validFiles.Add((imageName, imagePath));
var memoryStream = new MemoryStream();
// 创建zip归档
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
foreach (var (fileName, filePath) in validFiles)
{
try
{
// 在zip中创建条目
var entry = archive.CreateEntry(fileName, CompressionLevel.Optimal);
// 写入文件内容
using var entryStream = entry.Open();
using var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
await fileStream.CopyToAsync(entryStream);
}
catch (Exception ex)
{
}
}
}
memoryStream.Seek(0, SeekOrigin.Begin);
// 返回zip文件
return File(memoryStream, "application/zip", "1.zip");
//// 重置流位置
//return File(fileBytes, contentType, imageName);
}
catch (Exception ex)
{
return StatusCode(500, $"下载失败: {ex.Message}");
}
}
}
}