liaoxujun@qq.com
2023-08-01 57c0156fe021f9c690993e91da5dd280187f4fad
Merge branch 'master' of http://47.108.235.38:8080/r/DocumentService
1个文件已修改
9个文件已添加
391 ■■■■■ 已修改文件
.gitignore 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
DocumentFile.Service/Controllers/DocumentController.cs 66 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
DocumentFile.Service/DocumentFile.Service.csproj 16 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
DocumentFile.Service/IUploadService.cs 130 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
DocumentFile.Service/NLog.config 27 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
DocumentFile.Service/NLogProvider.cs 51 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
DocumentFile.Service/Program.cs 51 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
DocumentFile.Service/ReturnMsg.cs 31 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
DocumentFile.Service/appsettings.Development.json 8 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
DocumentFile.Service/appsettings.json 9 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
.gitignore
@@ -25,3 +25,5 @@
DocumentServiceAPI.Enum/obj/
/.vs
/DocumentServiceAPI.Web.Entry/appsettings.json
/DocumentFile.Service/bin
/DocumentFile.Service/obj
DocumentFile.Service/Controllers/DocumentController.cs
New file
@@ -0,0 +1,66 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
namespace DocumentFile.Service.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DocumentController : ControllerBase
    {
        private readonly IUploadService _uploadService;
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="uploadService"></param>
        public DocumentController(IUploadService uploadService)
        {
            _uploadService = uploadService;
        }
        /// <summary>
        /// 上传文件(word)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UploadDocument(IFormFile formFile)
        {
            ReturnMsg msg = new ReturnMsg();
            if(formFile.Length>0)
            {
                msg = await this._uploadService.HandleUploadWordFile(formFile);
            }
            else
            {
                msg.error = "请上传文件";
            }
            return new JsonResult(msg);
        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Download([FromBody] string url)
        {
            try
            {
                if (!string.IsNullOrEmpty(url))
                {
                    var _webRootPath = AppDomain.CurrentDomain.BaseDirectory;
                    return new FileStreamResult(new FileStream(_webRootPath + url, FileMode.Open), "application/octet-stream");// { FileDownloadName = FileName };
                }
            }
            catch (Exception ex)
            {
                NLogProvider.GetInstance().Error(ex);
            }
            return BadRequest();
        }
    }
}
DocumentFile.Service/DocumentFile.Service.csproj
New file
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Autofac" Version="7.0.1" />
    <PackageReference Include="Autofac.Extensions.DependencyInjection" Version="8.0.0" />
    <PackageReference Include="NLog" Version="5.2.2" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
  </ItemGroup>
</Project>
DocumentFile.Service/IUploadService.cs
New file
@@ -0,0 +1,130 @@
using System.IO.Compression;
namespace DocumentFile.Service
{
    public interface IUploadService
    {
        Task<ReturnMsg> HandleUploadWordFile(IFormFile iFormFile);
        Task<ReturnMsg> HandleUploadTemplateFile(IFormFile iFormFile);
        Task<ReturnMsg> HandleUploadImageFile(IFormFile iFormFile);
        //(string fileType, byte[] archiveData, string archiveName) DownloadFiles(string subDirectory);
    }
    public class UploadService : IUploadService
    {
        private readonly string _webRootPath;
        public UploadService()
        {
            _webRootPath = AppDomain.CurrentDomain.BaseDirectory;
        }
        /// <summary>
        /// 上传文件 辅助函数
        /// </summary>
        /// <param name="formFile"></param>
        /// <param name="folder"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        protected async virtual Task<ReturnMsg> HandleUploadFile(IFormFile formFile, string folder, params string[] format)
        {
            ReturnMsg msg = new ReturnMsg();
            try
            {
                var extensionName = Path.GetExtension(formFile.FileName)?.ToLower().Trim(); //获取后缀名
                if (format != null && format.Length > 0 && !format.ToList().Contains(extensionName.ToLower()))
                {
                    msg.error = "请上传后缀名为:" + string.Join("、", format) + " 格式的文件";
                }
                else
                {
                    var path = $"/upload/{folder}/{DateTime.Now:yyyyMMdd}";
                    var dir = this._webRootPath + path;
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                    var filename = $"ZC_{DateTime.Now:HHmmssfff}" + extensionName;
                    path += "/" + filename;
                    // 创建新文件
                    using var fs = File.Create(this._webRootPath+ path);
                    await formFile.CopyToAsync(fs);
                    // 清空缓冲区数据
                    fs.Flush();
                    msg.code = 1;
                    msg.url = path;
                }
            }
            catch (Exception er)
            {
                msg.code = -1;
                msg.error = "上传失败";
                NLogProvider.GetInstance().Error(er);
            }
            return msg;
        }
        /// <summary>
        /// 上传word文件
        /// </summary>
        /// <param name="iFormFile"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        public async virtual Task<ReturnMsg> HandleUploadWordFile(IFormFile iFormFile)
            => await this.HandleUploadFile(iFormFile, "Instance", ".doc",".docx");
        /// <summary>
        /// 上传word模板文件
        /// </summary>
        /// <param name="iFormFile"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        public async virtual Task<ReturnMsg> HandleUploadTemplateFile(IFormFile iFormFile)
            => await this.HandleUploadFile(iFormFile, "Template", ".doc", ".docx");
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="iFormFile"></param>
        /// <param name="folder"></param>
        /// <returns></returns>
        public async virtual Task<ReturnMsg> HandleUploadImageFile(IFormFile iFormFile)
            => await this.HandleUploadFile(iFormFile, "Photo", ".jpg", ".jpeg", ".png");
        /*, ".gif", ".jfif"*/
        ///// <summary>
        ///// 下载证书文件
        ///// 打包zip
        ///// </summary>
        ///// <param name="subDirectory"></param>
        ///// <returns></returns>
        //public (string fileType, byte[] archiveData, string archiveName) DownloadFiles(string path)
        //{
        //    using var memoryStream = new MemoryStream();
        //    using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
        //    {
        //        files.ForEach(file =>
        //        {
        //            var theFile = archive.CreateEntry(Path.GetFileName(file));
        //            using var binaryWriter = new BinaryWriter(theFile.Open());
        //            binaryWriter.Write(File.ReadAllBytes(file));
        //        });
        //    }
        //    return ("application/zip", memoryStream.ToArray(), zipName);
        //}
    }
}
DocumentFile.Service/NLog.config
New file
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd">
  <targets>
      <target xsi:type="File" name="info_file" fileName="${basedir}/logs/${shortdate}_info.log" layout="${longdate} ${uppercase:${level}} ${message}"/>
      <target xsi:type="File" name="error_file" fileName="${basedir}/logs/${shortdate}_error.log" layout="${longdate} ${uppercase:${level}} ${message} ${exception:stacktrace}" />
      <!--
    Write events to a file with the date in the filename.
    <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
            layout="${longdate} ${uppercase:${level}} ${message}" />
    -->
  </targets>
  <rules>
      <logger name="*" minlevel="Info" maxlevel="Info" writeTo="info_file" />
      <logger name="*" minlevel="Error" maxlevel="Error" writeTo="error_file" />
    <!--
    Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace)  to "f"
    <logger name="*" minlevel="Debug" writeTo="f" />
    -->
  </rules>
</nlog>
DocumentFile.Service/NLogProvider.cs
New file
@@ -0,0 +1,51 @@
using NLog;
namespace DocumentFile.Service
{
    /// <summary>
    /// 日志
    /// </summary>
    public class NLogProvider
    {
        private NLogProvider()
        {
            logger = LogManager.GetLogger("Logger");//.GetCurrentClassLogger();
        }
        private readonly Logger logger = null;
        private static NLogProvider logProvider = null;
        /// <summary>
        /// 静态实例
        /// </summary>
        /// <returns></returns>
        public static NLogProvider GetInstance()
        {
            if (logProvider == null)
            {
                logProvider = new NLogProvider();
            }
            return logProvider;
        }
        /// <summary>
        /// Info
        /// </summary>
        /// <param name="txt"></param>
        public void Info(string txt)
        {
            if (logger != null)
                logger.Info(txt);
        }
        /// <summary>
        /// Error
        /// </summary>
        /// <param name="er"></param>
        public void Error(Exception er)
        {
            if (logger != null)
                logger.Error(er);
        }
    }
}
DocumentFile.Service/Program.cs
New file
@@ -0,0 +1,51 @@
using Autofac;
using Autofac.Extensions.DependencyInjection;
using DocumentFile.Service;
using Microsoft.AspNetCore.Http.Features;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.WebHost.UseKestrel(options =>
{
    //options.Limits.MaxRequestLineSize = int.MaxValue;//HTTP 请求行的最大允许大小。 默认为 8kb
    //options.Limits.MaxRequestBufferSize = int.MaxValue;//请求缓冲区的最大大小。 默认为 1M
    //任何请求正文的最大允许大小(以字节为单位),默认 30,000,000 字节,大约为 28.6MB
    options.Limits.MaxRequestBodySize = 300 * 1024 * 1024; //限制请求长度
});
builder.Services.Configure<FormOptions>(options =>
{
    //默认上传大小限制
    options.MultipartBodyLengthLimit = 300 * 1024 * 1024;
    options.ValueLengthLimit = 300 * 1024 * 1024;
});
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
{
    //注册ioc
    builder.RegisterType<UploadService>().As<IUploadService>();
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
DocumentFile.Service/ReturnMsg.cs
New file
@@ -0,0 +1,31 @@
namespace DocumentFile.Service
{
    public class ReturnMsg
    {
        public ReturnMsg()
        {
            code = 0;
            count = 0;
        }
        /// <summary>
        /// 标识代码
        /// </summary>
        public int code { get; set; }
        /// <summary>
        /// 错误内容
        /// </summary>
        public string error { get; set; }
        /// <summary>
        /// 文件路径
        /// </summary>
        public string url { get; set; }
        /// <summary>
        /// 记录数量
        /// </summary>
        public int count { get; set; }
    }
}
DocumentFile.Service/appsettings.Development.json
New file
@@ -0,0 +1,8 @@
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  }
}
DocumentFile.Service/appsettings.json
New file
@@ -0,0 +1,9 @@
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}