.net core 文件接收服务接口的实现记录

1、新建一个类,用来处理接收到的文件信息,这个类是从网上找的

 public class UserFile
    {
        public string FileName { get; set; }
        public long Length { get; set; }
        public string Extension { get; set; }
        public string FileType { get; set; }

        private readonly static string[] Filters = { ".docx", ".pdf" };
        public bool IsValid => !string.IsNullOrEmpty(this.Extension) && Filters.Contains(this.Extension);

        private IFormFile file;
        public IFormFile File
        {
            get { return file; }
            set
            {
                if (value != null)
                {
                    this.file = value;

                    this.FileType = this.file.ContentType;
                    this.Length = this.file.Length;
                    this.Extension = this.file.FileName.Substring(file.FileName.LastIndexOf('.'));
                    if (string.IsNullOrEmpty(this.FileName))
                        this.FileName = this.file.FileName;
                }
            }
        }

        public async Task<string> SaveAs(string destinationDir = null)
        {
            if (this.file == null)
                throw new ArgumentNullException("没有需要保存的文件");

            if (destinationDir != null)
                Directory.CreateDirectory(destinationDir);

            var newName = DateTime.Now.Ticks;
            var newFile = Path.Combine(destinationDir ?? "", $"{newName}{this.Extension}");
            using (FileStream fs = new FileStream(newFile, FileMode.CreateNew))
            {
                await this.file.CopyToAsync(fs);
                fs.Flush();
            }

            return newFile;
        }
    }

2、新建一个api方法,注意上面的[RequestSizeLimit(1073741824)]是为了能1G以内的大文件上传

        [RequestSizeLimit(1073741824)]
        [HttpPost]
        public CommonReturnResult GetPositionInfoWithWordFile([FromForm] UserFile file, string projectId)
        {
            CommonReturnResult result = new CommonReturnResult { Success = false };
            if (file == null || !file.IsValid)
            {
                result.Success = false;
                result.Message = "不允许的文件格式";
            }

            string newFile = string.Empty;
            if (file != null)
            {
                var path = AppContext.BaseDirectory;

                var saveFolder = path + "\\TranlatedWordInfo\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + projectId;
                if (!Directory.Exists(saveFolder))
                {
                    Directory.CreateDirectory(saveFolder);
                }

                newFile = file.SaveAs(saveFolder).Result;


            }

            return result;
        }

3、修改Progress文件,增加ValueLengthLimit 和MultipartBodyLengthLimit的配置

    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
            {
                services.Configure<OcrConfigInfo>(hostContext.Configuration.GetSection(key: "OcrConfigInfo"));
                services.Configure<FormOptions>(x =>
                {
                    x.ValueLengthLimit = 1073741824;//配置文件大小限制 1GB
                    x.MultipartBodyLengthLimit = 1073741824;//配置文件大小限制 1GB
                });
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.Inject().UseStartup<Startup>();
            });
    }

4、发布后修改.net core自动生成的web.config 增加maxAllowedContentLength配置项

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
     <security>
      <requestFiltering>
        <!-- 1 GB -->
        <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
    </security>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath=".\BaseApi.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
    </system.webServer>
  </location>
</configuration>

 

5、测试调用

        static void Main(string[] args)
        {
            try
            {

                using (HttpClient client = new HttpClient())
                {
                    var content = new MultipartFormDataContent();
                    //添加字符串参数,参数名为qq
                    content.Add(new StringContent("111111111"), "projectId");

                    string path = @"C:\Users\wjx\Desktop\testUpload.docx"; //Path.Combine(System.Environment.CurrentDirectory, "1.png");
                                                                           //添加文件参数,参数名为files,文件名为123.png
                    content.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(path)), "file", "testUpload.docx");
                    var requestUri = "http://localhost:6001/ReWritePdf/GetPositionInfoWithWordFile";
                    var result = client.PostAsync(requestUri, content).Result.Content.ReadAsStringAsync().Result;

                    Console.WriteLine(result);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

 

posted @ 2021-10-23 13:23  星星c#  阅读(82)  评论(0编辑  收藏  举报