實現一個簡單檔案服務
阿新 • • 發佈:2022-03-04
Lazy FileServer
非常簡單的檔案服務,僅實現上傳然後生成url。
服務端
服務端提供統一介面,以便各子應用統一上傳檔案。
1. 安裝
Install-Package Lazy.FileServer.Server -Version 1.0.1
2. 配置
"FileServer": { "LocalBase": "C:\\upload", "HttpBase": "http://localhost", /* * 檔案路徑計算方式,分為Date和Hash * Date: * 格式: appName/year/month/day/上傳檔名 * 重複檔案處理: 重複檔案追加序號, 例如上傳a.txt, 存在重複,則編號為a.1.txt。 再次上傳則為a.2.txt * 示例: http://localhost/spider/2022/03/03/c220210105154619.348.jpg * * Hash: * 格式: appName/hash前兩位/hash3到4位/hash.副檔名 * 重複檔案處理: 重複hash會覆蓋 * 示例: http://localhost/spider/zq/I9/zqI98OULV8j60XbNSTTxQg==.jpg */ "FilePathCalculatorType": "hash", // 應用 "Apps": [ { "AppId": "1", "AppName": "spider", "AppKey": "123456" } ] }
builder.Services.AddLazyFileServer(builder.Configuration);
app.UseSimpleFileServer("/");
經過簡單的配置,一個上傳服務已經搭建好了。本例中通過http://localhost:5001/,header設定appid,appkey即可上傳。
3.自定義路徑計算方式
- 定義IFilePathCalculator實現類
public class CustomFilePathCalculator : IFilePathCalculator { public string Name { get { return "custom"; } } /// <summary> /// 直接返回檔名 /// </summary> /// <param name="input"></param> /// <returns></returns> public string Calculate(FilePathCalculatorInput input) { return input.FileName; } }
- 注入服務
builder.Services.AddLazyFileServer(builder.Configuration).AddFilePathCalculator<CustomFilePathCalculator>();
- 修改配置
"FilePathCalculatorType": "custom"
4.自定義應用查詢器
預設從AppSetting查詢.
- 定義CustomAppFinder實現類
public class CustomAppFinder : IAppFinder { private static List<AppInfo> Apps = new List<AppInfo>() { new AppInfo{ AppId = "1", AppKey = "654321", AppName = "spider" } }; public Task<AppInfo> FindAsync(string appid) { return Task.FromResult(Apps.FirstOrDefault(e => e.AppId == appid)); } }
- 替換預設服務
builder.Services.AddLazyFileServer(builder.Configuration).ReplaceAppFinder<CustomAppFinder>();
客戶端
前端應用理論上可以直接呼叫服務的上傳介面,但這樣會將appid,AppKey裸露在外界。因此需要各應用包裹下,提供一個上傳端點。
1. 安裝
Install-Package Lazy.FileServer.Client -Version 1.0.1
2. 示例
using Microsoft.AspNetCore.Mvc;
namespace Lazy.FileServer.Client.WebApi.Host.Controllers
{
[ApiController]
public class FileController : ControllerBase
{
private readonly ILogger<FileController> _logger;
private IHttpContextAccessor _httpContextAccessor;
public FileController(ILogger<FileController> logger, IHttpContextAccessor httpContextAccessor)
{
_logger = logger;
_httpContextAccessor = httpContextAccessor;
}
[HttpPost()]
[Route("Upload")]
public async Task<IEnumerable<string>> UploadAsync()
{
var client = new FileServerClient("http://localhost:5001", "1", "123456");
return await client.UploadAsync(_httpContextAccessor.HttpContext);
}
}
}