This repository was archived by the owner on Nov 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
Copy pathPicController.cs
74 lines (63 loc) · 2.41 KB
/
PicController.cs
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.eShopOnContainers.Services.Catalog.API.Infrastructure;
using System.IO;
using System.Net;
using System.Threading.Tasks;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace Microsoft.eShopOnContainers.Services.Catalog.API.Controllers
{
[ApiController]
public class PicController : ControllerBase
{
private readonly IWebHostEnvironment _env;
private readonly CatalogContext _catalogContext;
public PicController(IWebHostEnvironment env,
CatalogContext catalogContext)
{
_env = env;
_catalogContext = catalogContext;
}
[HttpGet]
[Route("api/v1/catalog/items/{catalogItemId:int}/pic")]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
// GET: /<controller>/
public async Task<ActionResult> GetImageAsync(int catalogItemId)
{
if (catalogItemId <= 0)
{
return BadRequest();
}
var item = await _catalogContext.CatalogItems
.SingleOrDefaultAsync(ci => ci.Id == catalogItemId);
if (item != null)
{
var webRoot = _env.WebRootPath;
var path = Path.Combine(webRoot, item.PictureFileName);
string imageFileExtension = Path.GetExtension(item.PictureFileName);
string mimetype = GetImageMimeTypeFromImageFileExtension(imageFileExtension);
var buffer = await System.IO.File.ReadAllBytesAsync(path);
return File(buffer, mimetype);
}
return NotFound();
}
private string GetImageMimeTypeFromImageFileExtension(string extension)
{
string mimetype = extension switch
{
".png" => "image/png",
".gif" => "image/gif",
".jpg" or ".jpeg" => "image/jpeg",
".bmp" => "image/bmp",
".tiff" => "image/tiff",
".wmf" => "image/wmf",
".jp2" => "image/jp2",
".svg" => "image/svg+xml",
_ => "application/octet-stream",
};
return mimetype;
}
}
}