Based on SqlSugar When file uploading is handled in the service layer of the development framework , We usually have two ways to deal with it , One is to store files in the local file system , One is through FTP Mode to the specified FTP Server . This processing should be configured by the program , Decide which way to use , In this case, we want to deal with it elastically , The option mode is adopted in the file upload module 【Options】 Handle regular uploads and FTP Configuration parameter information uploaded from the file .
Microsoft introduces Option mode , It is used to configure the settings used by the framework service . The option mode is defined by Microsoft.Extensions.OptionsNuGet Package implementation , except ASP.NET Core application , It also applies to any type of application , If you need to know , Microsoft documents The option mode is explained in detail .
One of the limitations of the option mode is that you can only parse ( Inject ) IOptions <MyOptions>
And the dependency injection configuration is completed ( That is, all modules ConfigureServices
Method to complete ) Get the option value after . If you are developing a module , You may need to enable developers to set some options , And use these options during the dependency injection registration phase . You may need to configure other services or change the registration code of dependency injection according to the option value .IOptions<> It's a singleton , So once it's generated , Unless it is changed by code , Its value is not updated .
1、 File upload processing
We introduced , There are two parts in the logic of file upload processing , One is local file processing , One is FTP Document processing , They choose that way , Information that depends on configuration parameters , As shown in the diagram below .
During local file processing , If it is Web API Method to invoke the service layer , Then in Web API In the same file system , If it is Winform The interface directly calls the service layer , That is to process files in the current system , This method can effectively manage our file information .
stay FTP During file processing , Is based on the information of the option parameters , call FluentFTP Class library to upload files .
stay Winform The interface for uploading files in the interface is as follows , It doesn't know which way to use , The details are determined by the configuration parameters .
All the attachment information is stored in the database , The files are stored in the corresponding folder , It can be managed, viewed and managed uniformly .
2、 Option mode 【Options】 To deal with
First of all, according to our treatment , Let's define an object , It is used to carry the information of upload parameters , As shown in the following code .
/// <summary> /// Option information for file upload processing /// </summary> public class UploadSettingOptions { /// <summary> /// Storage physical address that can be specified , Such as C:\\Attachment, If there is no configuration item AttachmentBasePath, Default to a relative directory . /// </summary> public string AttachmentBasePath { get; set; } /// <summary> /// Specify how attachments are uploaded , Such as ftp by FTP The way , If it is blank, it is the normal method /// </summary> public string AttachmentUploadType { get; set; } /// <summary> /// FTP Service address /// </summary> public string FtpServer { get; set; } /// <summary> /// FTP user name /// </summary> public string FtpUser { get; set; } /// <summary> /// FTP password /// </summary> public string FtpPassword { get; set; } /// <summary> /// FTP The basic path , If it can be specified as IIS The path of :http://www.iqidi.com:8000 , Easy to download and open /// </summary> public string FtpBaseUrl { get; set; } }
Then add... To the project Microsoft.Extensions.Options quote .
We define the file upload service class and its constructor , To facilitate the processing of option mode .
/// <summary> /// Upload attachment information Application layer service interface implementation /// </summary> public class FileUploadService : MyCrudService<FileUploadInfo,string, FileUploadPagedDto>, IFileUploadService { // Microsoft introduced the option model , It is used to configure the settings used by the framework service . The option mode is defined by Microsoft.Extensions.Options NuGet Package implementation // When you need to get an option value , take IOptions<TOption> Service injection into your class , Use it .Value Property gets the value . private readonly UploadSettingOptions _options; /// <summary> /// Parametric construction , Inject upload processing setting information /// </summary> /// <param name="options"></param> public FileUploadService(IOptions<UploadSettingOptions> options) { _options = options.Value; }
We see that the parameter information of an injection interface is provided here , After the parameters are injected and loaded , When we call the service class , You can use its option parameter information .
For example, our common upload processing methods are as follows .
/// <summary> /// Upload files ( Select the appropriate upload method according to the configuration file ) /// </summary> /// <param name="info"> file information ( Contains stream data )</param> /// <returns></returns> public async Task<CommonResult> Upload(FileUploadInfo info) { var uploadType = this._options.AttachmentUploadType; if (string.IsNullOrEmpty(uploadType)) { return await this.UploadByNormal(info); } else if (uploadType.Equals("ftp", StringComparison.OrdinalIgnoreCase)) { return await this.UploadByFTP(info); } else { throw new ArgumentException("AttachmentUploadType The configuration specified an invalid value , Please leave blank or fill in ftp."); } }
Let's read the information of the option parameters , To decide which way to upload files .
We are based on .net framewrok Of Winform project App.config Specify the following configuration information in
<appSettings> <!-- Save directory and FTP Configuration information --> <!-- Storage physical address that can be specified , Such as C:\\Attachment, If not configured, the default relative Directory .--> <add key="AttachmentBasePath" value="" /> <!-- Specify the default upload method for attachments , If FTP The way :ftp, If it is blank, it is the normal method --> <add key="AttachmentUploadType" value="" /> <!-- When it's not empty , Read the following FTP Information --> <add key="FtpServer" value="114.215.106.96" /> <add key="FtpUser" value="web2" /> <add key="FtpPassword" value="" /> <!-- Can be specified as HTTP perhaps FTP The path of , For downloading and viewing --> <add key="FtpBaseUrl" value="http://www.iqidi.com/ftp" /> </appSettings>
When the project starts , We need to inject the contents of the option parameters , To complete the reading of configuration file information .
/// <summary> /// The main entry point for the application . /// </summary> [STAThread] static void Main() { // IServiceCollection Responsible for registration IServiceCollection services = new ServiceCollection();// add to IApiUserSession Implementation class services.AddSingleton<IApiUserSession, ApiUserPrincipal>(); //CurrentPrincipal Realization way // Construct the corresponding environment UploadSettingOptions Information services.Configure<UploadSettingOptions>(option => { SetUploadOptions(option); });
/// <summary> /// Construct the corresponding environment UploadSettingOptions Information /// </summary> /// <returns></returns> private static UploadSettingOptions SetUploadOptions(UploadSettingOptions option) { var config = new AppConfig(); option.AttachmentBasePath = config.AppConfigGet("AttachmentBasePath"); option.AttachmentUploadType = config.AppConfigGet("AttachmentUploadType"); option.FtpServer = config.AppConfigGet("FtpServer"); option.FtpUser = config.AppConfigGet("FtpUser"); option.FtpPassword = config.AppConfigGet("FtpPassword"); option.FtpBaseUrl = config.AppConfigGet("FtpBaseUrl"); return option; }
That's it , stay .net framework Of WInform When the project starts , We have finished reading and loading the file upload option parameters , In this way FileUploadService The constructor inside , You can get the corresponding option parameter information object .
about .netcore The program , We know that its configuration information is appSettings.json, The following nodes are shown .
"UploadSettingOptions": { "AttachmentBasePath": "", // Storage physical address that can be specified , Such as C:\\Attachment, If not configured, the default relative Directory . "AttachmentUploadType": "", //ftp Or empty , If it is blank, it is the normal method "FtpServer": "114.215.106.96", //FTP Server address "FtpUser": "web2", //FTP account number "FtpPassword": "", //FTP password "FtpBaseUrl": "http://www.iqidi.com/ftp"// Can be specified as HTTP perhaps FTP The path of , For downloading and viewing }
For example, for us in Web API Initialization option object information for , The specific loaded code is as follows .
builder.Services.Configure<UploadSettingOptions>(builder.Configuration.GetSection("UploadSettingOptions"));
relative .net framework For the treatment of , Using extension functions simplifies a lot .
such , We can successfully obtain the corresponding configuration information in the service class for file upload processing .
/// <summary> /// Upload attachment information Application layer service interface implementation /// </summary> public class FileUploadService : MyCrudService<FileUploadInfo,string, FileUploadPagedDto>, IFileUploadService { // Microsoft introduced the option model , It is used to configure the settings used by the framework service . The option mode is defined by Microsoft.Extensions.Options NuGet Package implementation // When you need to get an option value , take IOptions<TOption> Service injection into your class , Use it .Value Property gets the value . private readonly UploadSettingOptions _options; /// <summary> /// Parametric construction , Inject upload processing setting information /// </summary> /// <param name="options"></param> public FileUploadService(IOptions<UploadSettingOptions> options) { _options = options.Value; }
We are using FTP When uploading files , Used FluentFtp The class library implementation FTP File upload processing , structure FTP The processing code of the object is as follows .
// Use FluentFTP operation FTP file var client = new FtpClient(this._options.FtpServer, this._options.FtpUser, this._options.FtpPassword); // If the configuration specifies a port , Use a specific port if (!string.IsNullOrEmpty(this._options.FtpServer) && this._options.FtpServer.Contains(":")) { string port = this._options.FtpServer.Split(':')[1]; if (!string.IsNullOrEmpty(port)) { client.Port = port.ToInt32(); } }
Upload FTP The code for the file is as follows .
// Determine the date time Directory ( Format :yyyy-MM), Create if it does not exist string savePath = string.Format("/{0}-{1:D2}/{2}", DateTime.Now.Year, DateTime.Now.Month, category); bool isExistDir = client.DirectoryExists(savePath); if (!isExistDir) { client.CreateDirectory(savePath); } // Use FTP Upload files // Avoid duplicate files , Use GUID name var ext = FileUtil.GetExtension(info.FileName); var newFileName = string.Format("{0}{1}", Guid.NewGuid().ToString(), ext);//FileUtil.GetFileName(file); savePath = savePath.UriCombine(newFileName); var uploaded = await client.UploadAsync(info.FileData, savePath, FtpRemoteExists.Overwrite, true); // After success , Write to database if (uploaded == FtpStatus.Success) {
By means of option parameters , We can configure the parameters IOC Processing call , Thus, the flexible configuration and reading operation of parameters are realized .
In other business processing service classes , If it involves some information that needs to be configured , We can all use this mode to configure the parameter content .
Series articles :