在 ASP.NET Core 中上传文件

简介

文件上传是指将媒体文件(本地文件或网络文件)从客户端上传至服务器存储。ASP.NET Core 支持使用缓冲的模型绑定(针对较小文件)和无缓冲的流式传输(针对较大文件)上传一个或多个文件。缓冲和流式传输是上传文件的两种常见方法。.

常见方法

缓冲

整个文件将读入一个 IFormFile。 IFormFile 是用于处理或保存文件的 C# 表示形式。

文件上传使用的磁盘和内存取决于并发文件上传的数量和大小。如果应用尝试缓冲过多上传,站点就会在内存或磁盘空间不足时崩溃。如果文件上传的大小或频率会消耗应用资源,请使用流式传输。

会将大于 64 KB 的所有单个缓冲文件从内存移到磁盘的临时文件。

用于较大请求的 ASPNETCORE_TEMP 临时文件将写入环境变量中命名的位置。如果未 ASPNETCORE_TEMP 定义,文件将写入当前用户的临时文件夹。

 [HttpPost, DisableRequestSizeLimit]
        public ActionResult UploadFile()
        {
            try
            {
                var file = Request.Form.Files[0];
                const string folderName = "Upload";
                var webRootPath = AppDomain.CurrentDomain.BaseDirectory;
                var newPath = Path.Combine(webRootPath, folderName);
                if (!Directory.Exists(newPath))
                {
                    Directory.CreateDirectory(newPath);
                }

                if (file.Length > 0)
                {
                    string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Value;
                    string fullPath = Path.Combine(newPath, fileName);
                    using (var stream = new FileStream(fullPath, FileMode.Create))
                    {
                        file.CopyTo(stream);
                    }
                    Console.WriteLine(fullPath);
                }

                return Json("Upload Successful.");
            }
            catch (Exception ex)
            {
                return Json("Upload Failed: " + ex.Message);
            }
        }

流式处理

从多部分请求收到文件,然后应用直接处理或保存它。流式传输无法显著提高性能。流式传输可降低上传文件时对内存或磁盘空间的需求。

验证

下面写个方法上传文件验证下

using System;using System.IO;namespace RestSharp.Samples.FileUpload.Client
{
    class Program
    {
        static void Main()
        {
            var client = new RestClient("http://localhost:5000");
            
            var request = new RestRequest("/api/upload", Method.POST);

            const string fileName = "ddd_book.jpg";
            var fileContent = File.ReadAllBytes(fileName);
            request.AddFileBytes(fileName, fileContent, fileName);

            var response = client.Execute(request);
            
            Console.WriteLine($"Response: {response.StatusCode}");
        }
    }
}