Lazy FileServer
非常簡單的檔案服務,僅實作上傳然后生成url,
碼云地址 Github地址
服務端
服務端提供統一介面,以便各子應用統一上傳檔案,
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);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/437843.html
標籤:.NET技术
上一篇:C# 模式匹配完全指南
下一篇:更改R中tibble列元素中的值
