-
-
Notifications
You must be signed in to change notification settings - Fork 852
/
PhysicalFileImageService.cs
76 lines (64 loc) · 2.63 KB
/
PhysicalFileImageService.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
75
76
// <copyright file="PhysicalFileImageService.cs" company="James Jackson-South">
// Copyright (c) James Jackson-South and contributors.
// Licensed under the Apache License, Version 2.0.
// </copyright>
namespace ImageSharp.Web.Services
{
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using ImageSharp.Memory;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
/// <summary>
/// Returns images stored in the local physical file system.
/// </summary>
public class PhysicalFileImageService : IImageService
{
/// <summary>
/// The hosting environment the application is running in.
/// </summary>
private readonly IHostingEnvironment environment;
/// <summary>
/// Initializes a new instance of the <see cref="PhysicalFileImageService"/> class.
/// </summary>
/// <param name="environment">The <see cref="IHostingEnvironment"/> used by this middleware</param>
public PhysicalFileImageService(IHostingEnvironment environment)
{
this.environment = environment;
}
/// <inheritdoc/>
public string Key { get; set; }
/// <inheritdoc/>
public IDictionary<string, string> Settings { get; set; } = new Dictionary<string, string>();
/// <inheritdoc/>
public async Task<bool> IsValidRequestAsync(HttpContext context, ILogger logger, string path)
{
// TODO: Either Write proper validation based on static FormatHelper (not written) in base library
// Or can we get this from the request header (preferred here)?
return await Task.FromResult(true);
}
/// <inheritdoc/>
public async Task<byte[]> ResolveImageAsync(HttpContext context, ILogger logger, string path)
{
// Path has already been correctly parsed before here.
IFileProvider fileProvider = this.environment.WebRootFileProvider;
IFileInfo fileInfo = fileProvider.GetFileInfo(path);
byte[] buffer;
// Check to see if the file exists.
if (!fileInfo.Exists)
{
return null;
}
using (Stream stream = fileInfo.CreateReadStream())
{
// Buffer is returned to the pool in the middleware
buffer = BufferDataPool.Rent((int)stream.Length);
await stream.ReadAsync(buffer, 0, (int)stream.Length);
}
return buffer;
}
}
}