当前位置:网站首页>在 ASP.NET Core 中上传文件
在 ASP.NET Core 中上传文件
2022-08-09 16:09: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}");
}
}
}
边栏推荐
- 嵌入式软件开发的特点和流程
- 原油等特殊期货开户要求和豁免
- uni-app覆盖组件样式h5生效,微信小程序不生效的问题
- A40 - 基于51单片机的GSM模块优化设计
- @AllArgsConstructor 和 @NoArgsConstructor
- 2022-08-09日报:做学术OR去公司 ? 想通这点,治好 AI 打工人的精神内耗
- 「我觉得AI领域乙烷」网友:你说的太多了,让AI来总结一下
- B46 - STM32太阳能充电智能心率监测骑行仪
- 5G NR Paging
- Leading practice | How the world's largest wine app uses design sprint to innovate the vivino model
猜你喜欢
随机推荐
面试官:Redis 大 key 要如何处理?
2022年中国第三方证券APP创新专题分析
【服务器数据恢复】SAN LUN映射出错导致文件系统数据丢失的数据恢复案例
ceph部署
聊聊基于docker部署的mysql如何进行数据恢复
A40 - 基于51单片机的GSM模块优化设计
Insert a number and sort "Suggested Favorites"
2019强网杯高明的黑客
Using Prometheus skillfully to extend the kubernetes scheduler
How to create DataFrame with feature importance from XGBClassifier made by GridSearchCV?
SQL trill interview: send you a universal template, to?(key, each user to log on to the maximum number of consecutive monthly)
Jenkins使用pipeline部署服务到远程服务器
No need to pay for the 688 Apple developer account, xcode13 packaged and exported ipa, and provided others for internal testing
如何让button中的内容分两行显示
<IDEA using tricks & & combined operation of common keys>
什么是控制板定制开发?
B46 - STM32太阳能充电智能心率监测骑行仪
网络——数字数据编码
LeetCode 413.等差数列划分
现在,怎么挑选舞台租赁LED显示屏?