Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Net5 WorkService inherits Quarzt and how Net5 handles file upload functions

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly shows you "Net5 WorkService inherits Quarzt and Net5 how to deal with file upload function", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "Net5 WorkService inherits Quarzt and Net5 how to deal with file upload function" this article.

The Net5 version uses Core as the underlying windowservice service of the non-framework framework.

Called WorkService in VS can be run as CMD or Windowservice, and it is easy to deploy.

Program.cs is the key configuration and startup item as follows

Using Microsoft.Extensions.Hosting;using Quartz;using WorkerService.Common;using WorkerService.Job;namespace WorkerService {public class Program {public static void Main (string [] args) {CreateHostBuilder (args) .Build () .Run () } public static IHostBuilder CreateHostBuilder (string [] args) = > Host.CreateDefaultBuilder (args). UseWindowsService () .ConfigureServices ((hostContext, services) = > {# region native work Service / / custom scheduling / / services.AddHostedService () # endregion # region quartz original version / / this version trigger job Schedule is the only association and cannot have multiple tasks / / services.AddQuartz in a group (Q = > / {/ / q.UseMicrosoftDependencyInjectionScopedJobFactory ()) / Create a "key" for the job / / var jobKey = new JobKey ("HelloTestJob"); / Register the job with the DI container / / q.AddJob (opts = > opts.WithIdentity (jobKey)) / Create a trigger for the job / / q.AddTrigger (opts = > opts / / .ForJob (jobKey) / / link to the HelloWorldJob / / .WithIdentity ("HelloTestJob-trigger") / / give the trigger a unique name / / .WithCronSchedule ("0CronSchedule") / / run every 1 seconds / /}); / / services.AddQuartzHostedService (Q = > q.WaitForJobsToComplete = true); # region quarzt optimized version / Register the job, loading the schedule from configuration / / q.AddJobAndTrigger (hostContext.Configuration, "0amp 1 *?") / / run once per second / / q.AddJobAndTrigger (hostContext.Configuration, "0swap 1 *?"); # region temperature and humidity SF6 infrared image upload services.AddQuartz (Q = > {q.UseMicrosoftDependencyInjectionScopedJobFactory () / / 0 beat per second 1 *? 00 *? / Register the job per hour, loading the schedule from configuration q.AddJobAndTrigger (hostContext.Configuration, "0 *?"); q.AddJobAndTrigger (hostContext.Configuration, "0 *?") Q.AddJobAndTrigger (hostContext.Configuration, "0 *?");}); services.AddQuartzHostedService (Q = > q.WaitForJobsToComplete = true);});}}

The original Host.CreateDefaultBuilder (args) needs to add .UseWindows Service () support for windowservice

Quarzt is called Quartz.Extensions.Hosting in NET5's nuget.

Services.AddHostedService (); is the original windows timed task version

The code is as follows, in await Task.Delay (1000, stoppingToken); set the number of milliseconds for timing start

Using Microsoft.Extensions.Hosting;using Microsoft.Extensions.Logging;using System;using System.IO;using System.Threading;using System.Threading.Tasks;namespace WorkerService.Job.Test {public class Worker: BackgroundService {private readonly ILogger _ logger; public Worker (ILogger logger) {_ logger = logger } protected override async Task ExecuteAsync (CancellationToken stoppingToken) {while (! stoppingToken.IsCancellationRequested) {_ logger.LogInformation ("Worker running at: {time}", DateTimeOffset.Now); FileStream stream = new FileStream (@ "d:\ aa.txt", FileMode.Create); / / fileMode specifies whether to read or write StreamWriter writer = new StreamWriter (stream) Writer.WriteLine ("123456" + DateTimeOffset.Now); / / write a line that wraps writer.Write ("abc") automatically after writing; / / does not wrap writer.WriteLine ("ABC"); writer.Close (); / / frees memory stream.Close () / / Free memory await Task.Delay (1000, stoppingToken);}

Original version of quartz (screenshot of program.cs code)

In the current version of quartz 3.3.3, it seems impossible to integrate multiple Job jobs under one Key. So each job needs a registration. The optimized version is recommended.

Quarzt optimized version (screenshot of program.cs code)

The original version is encapsulated. A new unique instance is registered with each call.

Here are the help classes

Using Microsoft.Extensions.Configuration;using Quartz;using System;namespace WorkerService.Common {public static class ServiceCollectionQuartzConfiguratorExtensions {public static void AddJobAndTrigger (this IServiceCollectionQuartzConfigurator quartz, IConfiguration config, string cronSchedule) where T: IJob {/ / Use the name of the IJob as the appsettings.json key string jobName = typeof (T) .Name / / Try and load the schedule from configuration var configKey = $"Quartz: {jobName}"; / / var cronSchedule = config [configKey]; / / Some minor validation if (string.IsNullOrEmpty (cronSchedule)) {throw new Exception ($"No Quartz.NET Cron schedule found for job in configuration at {configKey}") } / / register the job as before var jobKey = new JobKey (jobName); quartz.AddJob (opts = > opts.WithIdentity (jobKey)); quartz.AddTrigger (opts = > opts .ForJob (jobKey) .WithIdentity (jobName + "- trigger") .WithCronSchedule (cronSchedule)); / / use the schedule from configuration}

The following is Job

Using Microsoft.Extensions.Logging;using Quartz;using System;using System.IO;using System.Threading.Tasks;namespace WorkerService.Job.Test {[DisallowConcurrentExecution] public class HelloTestJob2: IJob {private readonly ILogger _ logger; public HelloTestJob2 (ILogger logger) {_ logger = logger;} public Task Execute (IJobExecutionContext context) {FileStream stream = new FileStream (@ "d:\ aa1.txt", FileMode.Create) / / fileMode specifies whether to read or write StreamWriter writer = new StreamWriter (stream); writer.WriteLine ("123456aaa" + DateTimeOffset.Now); / / write a line that wraps writer.Write ("abc") automatically after writing; / / does not wrap writer.WriteLine ("ABC"); writer.Close (); / / frees memory stream.Close () / / Free memory return Task.CompletedTask;}

The program runs periodically within the Task Execute (IJobExecutionContext context) method according to the run time set by Corn

And then it's kind of funny, everybody doesn't use Net5. Write service to upload files. When you encounter a problem, search NET5 to deal with the problem of file upload, but it is all blank. Then I'll have to write my own solution.

The HTTPHelper.cs code for uploading images on the client is as follows

/ upload file / request address / File path (with file name) / public static string HttpPostFile (string url, string path) {/ / set parameter HttpWebRequest request = WebRequest.Create (url) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer () Request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = "POST"; string boundary= DateTime.Now.Ticks.ToString ("X"); / / Random Separator request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary; byte [] itemBoundaryBytes = Encoding.UTF8.GetBytes ("\ r\ nmi -" + boundary + "\ r\ n") Byte [] endBoundaryBytes = Encoding.UTF8.GetBytes ("\ r\ nWhen -" + boundary + "- -\ r\ n"); int pos = path.LastIndexOf ("\\"); string fileName = path.Substring (pos + 1); / / request header information StringBuilder sbHeader = new StringBuilder ("Content-Disposition:form-data;name=\" file\ ") Filename=\ "{0}\"\ r\ nContent-Type:application/octet-stream\ r\ r\ n\ n fileName); byte [] postHeaderBytes = Encoding.UTF8.GetBytes (sbHeader.ToString ()); StringBuilder builder = new StringBuilder ($"Content-Disposition:form-data;name=\" subPath\ "\ r\ r\ ntmswechat"); byte [] postHeaderBytestwo = Encoding.UTF8.GetBytes (builder.ToString ()) FileStream fs = new FileStream (path, FileMode.Open, FileAccess.Read); byte [] bArr = new byte [fs.Length]; fs.Read (bArr, 0, bArr.Length); fs.Close (); Stream postStream = request.GetRequestStream (); postStream.Write (itemBoundaryBytes, 0, itemBoundaryBytes.Length); postStream.Write (postHeaderBytes, 0, postHeaderBytes.Length) PostStream.Write (bArr, 0, bArr.Length); postStream.Write (itemBoundaryBytes, 0, itemBoundaryBytes.Length); postStream.Write (postHeaderBytestwo, 0, postHeaderBytestwo.Length); postStream.Write (endBoundaryBytes, 0, endBoundaryBytes.Length); postStream.Close (); / / send the request and get the corresponding response data HttpWebResponse response = request.GetResponse () as HttpWebResponse / / it was not until the request.GetResponse () program began to send the Post request Stream instream = response.GetResponseStream () to the target web page; StreamReader sr = new StreamReader (instream, Encoding.UTF8); / / returned the result web page (html) code string content = sr.ReadToEnd (); return content;}

The key point is the reception on the server side, and part of the code is as follows

Try {var files = Request.Form.Files; if (files! = null) {var file = files [0]; var location = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + $"Image\\" + file.FileName If (! Directory.Exists (System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + $"Image\\") / / determines whether the upload folder exists. If not, create {Directory.CreateDirectory (System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + $"Image\\"). / / create a folder} using (var stream = new FileStream (location, FileMode.Create)) {await file.CopyToAsync (stream); result = 1 }} / / using (var reader = new StreamReader (Request.Body)) / / read from the body / / {/ / var body = await reader.ReadToEndAsync () / /}} catch (Exception e) {throw;}

Even if you are using file stream upload, not form submission. But your file is still in Request.Form.Files!

But you can also read the stream through Request.body

/ / using (var reader = new StreamReader (Request.Body)) / / read / / {/ / var body = await reader.ReadToEndAsync () from the body; / /} above is all the content of this article "Net5 WorkService inherits Quarzt and how Net5 handles file upload function". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report