当前位置:网站首页>在 ASP.NET Core 中上传文件
在 ASP.NET Core 中上传文件
2022-08-09 00:36:00 【dotNET跨平台】
简介
文件上传是指将媒体文件(本地文件或网络文件)从客户端上传至服务器存储。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}");
}
}
}边栏推荐
猜你喜欢
随机推荐
Dapr学习(4)之eShopOnDapr部署(Rancher2.63&k3s)
Unified identity management platform IAM single sign-on process and third-party interface design scheme
关于cordova的InAppBrowser插件的几点问题
2021 icpc 上海 H. Life is a Game
【学习-目标检测】目标检测之—FPN+Cascade+Libra
一道dp的三次优化(时间+空间)
GaN图腾柱无桥 Boost PFC(单相)二 (公式推到理解篇)
软考总结博客
"Replay" interview BAMT came back to sort out 398 high-frequency interview questions to help you get a high salary offer
5-4 Seaborn 线性回归绘图
wordpress入门基本操作,网站安全防护及常用插件(建站必看教程)
Network In Network学习记录
bitset和bool哪个更快
基本控件属性
#468. 函数求和
在Ubuntu/Linux环境下使用MySQL:修改数据库sql_mode,可解决“this is incompatible with sql_mode=only_full_group_by”问题
微信企业号开发之获取AccessToken
数学模型建立常用方法
小G砍树 (换根dp)
线程与线程池









