ASP.NET Core單文件和多文件上傳並保存到服務端


前言:

  在我們日常開發中,關於圖片,視頻,音頻,文檔等相關文件上傳並保存到服務端中是非常常見的一個功能,今天主要是把自己在開發中常用的兩種方式記錄下來方便一下直接使用,並且希望能夠幫助到有需要的同學!

一、配置ASP.NET Core中的靜態文件:

簡單概述:

  在ASP.NET Core應用中靜態資源文件需要進行相應的配置才能夠提供給客戶端直接使用。

詳情描述請參考官方文檔:

https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/static-files?view=aspnetcore-3.1

簡單配置,提供 Web 根目錄內的文件:

調用 Startup.Configure中的UseStaticFiles 方法配置:

public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles();
}

二、文件服務器和應用程序配置(IIS,Kestrel):

詳情描述,請參考官方文檔說明:

https://docs.microsoft.com/zh-cn/aspnet/core/mvc/models/file-uploads?view=aspnetcore-3.1#server-and-app-configuration

多部分正文長度限制:

MultipartBodyLengthLimit 設置每個多部分正文的長度限制。 分析超出此限制的窗體部分時,會引發 InvalidDataException。 默認值為 134,217,728 (128 MB)。 使用 MultipartBodyLengthLimit 中的 Startup.ConfigureServices 設置自定義此限制:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<FormOptions>(options =>
    {
        // Set the limit to 256 MB
        options.MultipartBodyLengthLimit = 268435456;
    });
}

Kestrel 最大請求正文大小:

對於 Kestrel 托管的應用,默認的最大請求正文大小為 30,000,000 個字節,約為 28.6 MB。 使用 MaxRequestBodySize Kestrel 服務器選項自定義限制:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureKestrel((context, options) =>
        {
            // Handle requests up to 50 MB
            options.Limits.MaxRequestBodySize = 52428800;
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

IIS 內容長度限制:

默認的請求限制 (maxAllowedContentLength) 為 30,000,000 字節,大約 28.6 MB。 請在 web.config 文件中自定義此限制:

<system.webServer>
  <security>
    <requestFiltering>
      <!-- Handle requests up to 50 MB -->
      <requestLimits maxAllowedContentLength="52428800" />
    </requestFiltering>
  </security>
</system.webServer>

三、單文件上傳:

using System;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace FileUploadManage.Controllers
{
    /// <summary>
    /// 圖片,視頻,音頻,文檔等相關文件通用上傳服務類
    /// </summary>
    public class FileUploadController : Controller
    {
        private static IHostingEnvironment _hostingEnvironment;

        public FileUploadController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        /// <summary>
        /// 單文件上傳(ajax,Form表單都適用)
        /// </summary>
        /// <returns></returns>
        public JsonResult SingleFileUpload()
        {
            var formFile = Request.Form.Files[0];//獲取請求發送過來的文件
            var currentDate = DateTime.Now;
            var webRootPath = _hostingEnvironment.WebRootPath;//>>>相當於HttpContext.Current.Server.MapPath("") 

            try
            {
                var filePath = $"/UploadFile/{currentDate:yyyyMMdd}/";

                //創建每日存儲文件夾
                if (!Directory.Exists(webRootPath + filePath))
                {
                    Directory.CreateDirectory(webRootPath + filePath);
                }

                if (formFile != null)
                {
                    //文件后綴
                    var fileExtension = Path.GetExtension(formFile.FileName);//獲取文件格式,拓展名

                    //判斷文件大小
                    var fileSize = formFile.Length;

                    if (fileSize > 1024 * 1024 * 10) //10M TODO:(1mb=1024X1024b)
                    {
                        return new JsonResult(new { isSuccess = false, resultMsg = "上傳的文件不能大於10M" });
                    }

                    //保存的文件名稱(以名稱和保存時間命名)
                    var saveName = formFile.FileName.Substring(0, formFile.FileName.LastIndexOf('.')) + "_" + currentDate.ToString("HHmmss") + fileExtension;

                    //文件保存
                    using (var fs = System.IO.File.Create(webRootPath + filePath + saveName))
                    {
                        formFile.CopyTo(fs);
                        fs.Flush();
                    }

                    //完整的文件路徑
                    var completeFilePath = Path.Combine(filePath, saveName);

                    return new JsonResult(new { isSuccess = true, returnMsg = "上傳成功", completeFilePath = completeFilePath });
                }
                else
                {
                    return new JsonResult(new { isSuccess = false, resultMsg = "上傳失敗,未檢測上傳的文件信息~" });
                }

            }
            catch (Exception ex)
            {
                return new JsonResult(new { isSuccess = false, resultMsg = "文件保存失敗,異常信息為:" + ex.Message });
            }
        }

        /// <summary>
        /// Form表單之單文件上傳
        /// </summary>
        /// <param name="formFile">form表單文件流信息</param>
        /// <returns></returns>
        public JsonResult FormSingleFileUpload(IFormFile formFile)
        {
            var currentDate = DateTime.Now;
            var webRootPath = _hostingEnvironment.WebRootPath;//>>>相當於HttpContext.Current.Server.MapPath("") 

            try
            {
                var filePath = $"/UploadFile/{currentDate:yyyyMMdd}/";

                //創建每日存儲文件夾
                if (!Directory.Exists(webRootPath + filePath))
                {
                    Directory.CreateDirectory(webRootPath + filePath);
                }

                if (formFile != null)
                {
                    //文件后綴
                    var fileExtension = Path.GetExtension(formFile.FileName);//獲取文件格式,拓展名

                    //判斷文件大小
                    var fileSize = formFile.Length;

                    if (fileSize > 1024 * 1024 * 10) //10M TODO:(1mb=1024X1024b)
                    {
                        return new JsonResult(new { isSuccess = false, resultMsg = "上傳的文件不能大於10M" });
                    }

                    //保存的文件名稱(以名稱和保存時間命名)
                    var saveName = formFile.FileName.Substring(0, formFile.FileName.LastIndexOf('.')) + "_" + currentDate.ToString("HHmmss") + fileExtension;

                    //文件保存
                    using (var fs = System.IO.File.Create(webRootPath + filePath + saveName))
                    {
                        formFile.CopyTo(fs);
                        fs.Flush();
                    }

                    //完整的文件路徑
                    var completeFilePath = Path.Combine(filePath, saveName);

                    return new JsonResult(new { isSuccess = true, returnMsg = "上傳成功", completeFilePath = completeFilePath });
                }
                else
                {
                    return new JsonResult(new { isSuccess = false, resultMsg = "上傳失敗,未檢測上傳的文件信息~" });
                }

            }
            catch (Exception ex)
            {
                return new JsonResult(new { isSuccess = false, resultMsg = "文件保存失敗,異常信息為:" + ex.Message });
            }

        }
    }
} 

四、多文件上傳:

using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Internal;

namespace FileUploadManage.Controllers
{
    /// <summary>
    /// 圖片,視頻,音頻,文檔等相關文件通用上傳服務類
    /// </summary>
    public class FileUploadController : Controller
    {
        private static IHostingEnvironment _hostingEnvironment;

        public FileUploadController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        /// <summary>
        ///  多文件上傳
        /// </summary>
        /// <param name="formCollection">表單集合值</param>
        /// <returns>服務器存儲的文件信息</returns>

        public JsonResult MultiFileUpload(IFormCollection formCollection)
        {
            var currentDate = DateTime.Now;
            var webRootPath = _hostingEnvironment.WebRootPath;//>>>相當於HttpContext.Current.Server.MapPath("") 
            var uploadFileRequestList = new List<UploadFileRequest>();
            try
            {
                //FormCollection轉化為FormFileCollection
                var files = (FormFileCollection)formCollection.Files;

                if (files.Any())
                {
                    foreach (var file in files)
                    {
                        var uploadFileRequest = new UploadFileRequest();

                        var filePath = $"/UploadFile/{currentDate:yyyyMMdd}/";

                        //創建每日存儲文件夾
                        if (!Directory.Exists(webRootPath + filePath))
                        {
                            Directory.CreateDirectory(webRootPath + filePath);
                        }

                        //文件后綴
                        var fileExtension = Path.GetExtension(file.FileName);//獲取文件格式,拓展名

                        //判斷文件大小
                        var fileSize = file.Length;

                        if (fileSize > 1024 * 1024 * 10) //10M TODO:(1mb=1024X1024b)
                        {
                            continue;
                        }

                        //保存的文件名稱(以名稱和保存時間命名)
                        var saveName = file.FileName.Substring(0, file.FileName.LastIndexOf('.')) + "_" + currentDate.ToString("HHmmss") + fileExtension;

                        //文件保存
                        using (var fs = System.IO.File.Create(webRootPath + filePath + saveName))
                        {
                            file.CopyTo(fs);
                            fs.Flush();
                        }

                        //完整的文件路徑
                        var completeFilePath = Path.Combine(filePath, saveName);

                        uploadFileRequestList.Add(new UploadFileRequest()
                        {
                            FileName = saveName,
                            FilePath = completeFilePath
                        });
                    }
                }
                else
                {
                    return new JsonResult(new { isSuccess = false, resultMsg = "上傳失敗,未檢測上傳的文件信息~" });
                }
            }
            catch (Exception ex)
            {
                return new JsonResult(new { isSuccess = false, resultMsg = "文件保存失敗,異常信息為:" + ex.Message });
            }

            if (uploadFileRequestList.Any())
            {
                return new JsonResult(new { isSuccess = true, returnMsg = "上傳成功", filePathArray = uploadFileRequestList });
            }
            else
            {
                return new JsonResult(new { isSuccess = false, resultMsg = "網絡打瞌睡了,文件保存失敗" });
            }
        }

    }

    /// <summary>
    /// 對文件上傳響應模型
    /// </summary>
    public class UploadFileRequest
    {
        /// <summary>
        /// 文件名稱
        /// </summary>
        public string FileName { get; set; }

        /// <summary>
        /// 文件路徑
        /// </summary>
        public string FilePath { get; set; }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM