溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

ASP.NET Core文件文件如何上傳和保存到服務(wù)端

發(fā)布時間:2021-03-10 16:56:54 來源:億速云 閱讀:945 作者:TREX 欄目:開發(fā)技術(shù)

這篇文章主要介紹“ASP.NET Core文件文件如何上傳和保存到服務(wù)端”,在日常操作中,相信很多人在ASP.NET Core文件文件如何上傳和保存到服務(wù)端問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”ASP.NET Core文件文件如何上傳和保存到服務(wù)端”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!

ASP.NET 是什么

ASP.NET 是開源,跨平臺,高性能,輕量級的 Web 應(yīng)用構(gòu)建框架,常用于通過 HTML、CSS、JavaScript 以及服務(wù)器腳本來構(gòu)建網(wǎng)頁和網(wǎng)站。


前言:

  在我們?nèi)粘i_發(fā)中,關(guān)于圖片,視頻,音頻,文檔等相關(guān)文件上傳并保存到服務(wù)端中是非常常見的一個功能,今天主要是把自己在開發(fā)中常用的兩種方式記錄下來方便一下直接使用,并且希望能夠幫助到有需要的同學(xué)!

一、配置ASP.NET Core中的靜態(tài)文件:

簡單概述:

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

詳情描述請參考官方文檔:
https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/static-files?view=aspnetcore-3.1

簡單配置,提供 Web 根目錄內(nèi)的文件:

調(diào)用 Startup.Configure中的UseStaticFiles 方法配置:

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

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

詳情描述,請參考官方文檔說明:
https://docs.microsoft.com/zh-cn/aspnet/core/mvc/models/file-uploads?view=aspnetcore-3.1#server-and-app-configuration

多部分正文長度限制:

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

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

Kestrel 最大請求正文大?。?/strong>

對于 Kestrel 托管的應(yīng)用,默認的最大請求正文大小為 30,000,000 個字節(jié),約為 28.6 MB。 使用 MaxRequestBodySize Kestrel 服務(wù)器選項自定義限制:

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 內(nèi)容長度限制:

默認的請求限制 (maxAllowedContentLength) 為 30,000,000 字節(jié),大約 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.Mvc;

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

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

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

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

        //創(chuàng)建每日存儲文件夾
        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>
  /// 圖片,視頻,音頻,文檔等相關(guān)文件通用上傳服務(wù)類
  /// </summary>
  public class FileUploadController : Controller
  {
    private static IHostingEnvironment _hostingEnvironment;

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

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

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

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

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

            //創(chuàng)建每日存儲文件夾
            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 = "網(wǎng)絡(luò)打瞌睡了,文件保存失敗" });
      }
    }

  }

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

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

到此,關(guān)于“ASP.NET Core文件文件如何上傳和保存到服務(wù)端”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI