ASP.NET Web API 是一个用于构建 HTTP 服务的框架,可以用于创建 RESTful 服务。作为映像服务,它能够处理图片的上传、存储、处理和分发。
[ApiController]
[Route("api/images")]
public class ImagesController : ControllerBase
{
private readonly IWebHostEnvironment _environment;
private readonly IImageService _imageService;
public ImagesController(IWebHostEnvironment environment, IImageService imageService)
{
_environment = environment;
_imageService = imageService;
}
[HttpPost("upload")]
public async Task<IActionResult> UploadImage(IFormFile file)
{
if (file == null || file.Length == 0)
return BadRequest("No file uploaded.");
var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif" };
var fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
if (string.IsNullOrEmpty(fileExtension) || !allowedExtensions.Contains(fileExtension))
return BadRequest("Invalid file type.");
try
{
var imageUrl = await _imageService.SaveImageAsync(file);
return Ok(new { Url = imageUrl });
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}
[HttpGet("{id}")]
public IActionResult GetImage(string id)
{
try
{
var imagePath = _imageService.GetImagePath(id);
if (imagePath == null)
return NotFound();
var imageFileStream = System.IO.File.OpenRead(imagePath);
return File(imageFileStream, "image/jpeg"); // 根据实际类型调整
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}
}
public interface IImageService
{
Task<string> SaveImageAsync(IFormFile file);
string GetImagePath(string id);
Task<Stream> GetImageThumbnailAsync(string id, int width, int height);
Task<bool> DeleteImageAsync(string id);
}
原因:默认请求大小限制较小
解决方案:
// 在Program.cs或Startup.cs中配置
builder.Services.Configure<FormOptions>(options =>
{
options.MultipartBodyLengthLimit = 104857600; // 100MB
});
原因:同步处理大量图片请求
解决方案:
原因:所有图片存储在单一服务器
解决方案:
原因:从不同域访问API
解决方案:
// 启用CORS
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
// 然后在中间件中使用
app.UseCors("AllowAll");
public async Task<Stream> GenerateThumbnailAsync(Stream imageStream, int width, int height)
{
using var image = await Image.LoadAsync(imageStream);
image.Mutate(x => x.Resize(new ResizeOptions
{
Size = new Size(width, height),
Mode = ResizeMode.Max
}));
var memoryStream = new MemoryStream();
await image.SaveAsJpegAsync(memoryStream);
memoryStream.Position = 0;
return memoryStream;
}
public async Task<Stream> AddWatermarkAsync(Stream imageStream, string watermarkText)
{
using var image = await Image.LoadAsync(imageStream);
image.Mutate(x => x.DrawText(
watermarkText,
SystemFonts.CreateFont("Arial", 30),
Color.White.WithAlpha(0.75f),
new PointF(10, 10)));
var memoryStream = new MemoryStream();
await image.SaveAsJpegAsync(memoryStream);
memoryStream.Position = 0;
return memoryStream;
}
ASP.NET Web API 作为映像服务提供了灵活、可扩展的解决方案,可以根据需求进行定制和扩展。
没有搜到相关的文章