using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using DiuDiuTemplate.Domain.WebHelpers.Base;
using DiuDiuTemplate.Infrastructure.Common.Helpers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Net.Http.Headers; namespace DiuDiuTemplate.UserApi.Controllers
{
public class FileUpLoadController : ApiControllerBase
{
private IWebHostEnvironment _webhostEnv; public FileUpLoadController(IWebHostEnvironment webhostEnv)
{
_webhostEnv = webhostEnv;
} /// <summary>
/// 上传文件到API服务器 较小的文件上传 20M
/// </summary>
/// <returns>返回文件的saveKeys</returns>
[HttpPost]
[RequestSizeLimit()]
[AllowAnonymous]
public async Task<List<string>> UploadFile(List<IFormFile> files)
{
List<string> saveKeys = new List<string>(); foreach (var formFile in files)
{
//相对路径
string saveKey = GetRelativePath(formFile.FileName); //完整路径
string path = GetAbsolutePath(saveKey);
await WriteFileAsync(formFile.OpenReadStream(), path);
saveKeys.Add(saveKey);
}
return saveKeys;
}
/// <summary>
/// 大文件上传到API服务器
/// 流式接收文件,不缓存到服务器内存/// </summary>
/// <att name="DisableRequestSizeLimit">不限制请求的大小</att>
/// <returns>返回文件的saveKeys</returns>
[HttpPost]
[Route("BigFileUpload")]
[DisableRequestSizeLimit]
[AllowAnonymous]
public async Task<List<string>> BigFileUpload()
{
List<string> saveKeys = new List<string>(); //获取boundary
var boundary = HeaderUtilities.RemoveQuotes(MediaTypeHeaderValue.Parse(Request.ContentType).Boundary).Value;
//得到reader
var reader = new MultipartReader(boundary, HttpContext.Request.Body); var section = await reader.ReadNextSectionAsync(); //读取 section 每个formData算一个 section 多文件上传时每个文件算一个 section
while (section != null)
{
var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);
if (hasContentDispositionHeader)
{
if (contentDisposition.IsFileDisposition())
{
//相对路径
string saveKey = GetRelativePath(contentDisposition.FileName.Value);
//完整路径
string path = GetAbsolutePath(saveKey); await WriteFileAsync(section.Body, path);
saveKeys.Add(saveKey);
}
else
{
string str = await section.ReadAsStringAsync();
}
}
section = await reader.ReadNextSectionAsync();
}
return saveKeys; }
/// <summary>
/// 写文件导到磁盘
/// </summary>
/// <param name="stream">流</param>
/// <param name="path">文件保存路径</param>
/// <returns></returns>
private static async Task<int> WriteFileAsync(System.IO.Stream stream, string path)
{
const int FILE_WRITE_SIZE = ;//写出缓冲区大小
int writeCount = ;
using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Write, FILE_WRITE_SIZE, true))
{
byte[] byteArr = new byte[FILE_WRITE_SIZE];
int readCount = ;
while ((readCount = await stream.ReadAsync(byteArr, , byteArr.Length)) > )
{
await fileStream.WriteAsync(byteArr, , readCount);
writeCount += readCount;
}
}
return writeCount;
} /// <summary>
/// 获取相对路径
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
private string GetRelativePath(string fileName)
{
string str1 = CommonHelper.GetGuid().Replace("-", "");
int start = fileName.LastIndexOf('.');
//相对路径
return $"/upload/{DateTime.Now.Year}/{DateTime.Now.Month}/{DateTime.Now.Day}/{str1}{fileName.Substring(start, fileName.Length - start)}"; }
/// <summary>
/// 获取完整路径
/// </summary>
/// <param name="relativePath"></param>
/// <returns></returns>
private string GetAbsolutePath(string relativePath)
{
//完整路径
string path = Path.Join(_webhostEnv.WebRootPath, relativePath); string directoryPath = Path.GetDirectoryName(path);
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
} return path; }
}
}

小文件上传和大文件上传;

最后记得要添加静态文件中间件

app.UseStaticFiles();

API默认没有这个中间件

还可以设置一些上传大小的限制,这个只是程序的配置,如果部署到IIS等,还需要修改IIS的上传文件限制,这里只实现代码部分;

  

services.Configure<FormOptions>(x =>
{
  x.ValueLengthLimit = int.MaxValue;
  x.MultipartBodyLengthLimit = int.MaxValue;
  x.MultipartHeadersLengthLimit = int.MaxValue;
});

.net core 上传大文件的更多相关文章

  1. ASP.NET Core 上传大文件无法接收的问题

    解决办法:在API项目中配置 1. 在 web.config 文件中 <system.webServer>里加入 <security> <requestFiltering ...

  2. asp.net core流式上传大文件

    asp.net core流式上传大文件 首先需要明确一点就是使用流式上传和使用IFormFile在效率上没有太大的差异,IFormFile的缺点主要是客户端上传过来的文件首先会缓存在服务器内存中,任何 ...

  3. 日常采坑:.NetCore上传大文件

    一..NetCore上传大文件 .NetCore3.1 webapi 本地测试上传时,遇到一个坑,大点的文件直接失败,根本不走控制器方法. 二.大文件上传配置 IFormFile方式,vs IIS E ...

  4. 批量上传文件或者上传大文件时 gateWay报错DataBufferLimitException: Exceeded limit on max bytes to buffer : 262144

    一.描述 最近在批量上传文件时网关出现了异常,后面发现上传大文件也会出现文件超过256发生异常,异常信息如下: org.springframework.core.io.buffer.DataBuffe ...

  5. [Asp.net]Uploadify上传大文件,Http error 404 解决方案

    引言 之前使用Uploadify做了一个上传图片并预览的功能,今天在项目中,要使用该插件上传大文件.之前弄过上传图片的demo,就使用该demo进行测试.可以查看我的这篇文章:[Asp.net]Upl ...

  6. php 上传大文件配置upload_max_filesize和post_max_size选项

    php 上传大文件配置upload_max_filesize和post_max_size选项 (2014-04-29 14:42:11) 转载▼ 标签: php.ini upload _files[f ...

  7. PHP上传大文件 分割文件上传

    最近遇到这么个情况,需要将一些大的文件上传到服务器,我现在拥有的权限是只能在一个网页版的文件管理系统来进行操作,可以解压,可以压缩,当然也可以用它来在线编辑.php文件. 文件有40M左右,但是服务器 ...

  8. ASP.NET上传大文件的问题

    原文:http://www.cnblogs.com/wolf-sun/p/3657241.html?utm_source=tuicool&utm_medium=referral 引言 之前使用 ...

  9. php 上传大文件主要涉及配置upload_max_filesize和post_max_size两个选项

    php 上传大文件主要涉及配置 upload_max_filesize 和post_max_size两个选项   今天在做上传的时候出现一个非常怪的问题,有时候表单提交可以获取到值,有时候就获取不到了 ...

随机推荐

  1. 《C程序设计语言》 练习2-3

    问题描述 < class="title-article"> 练习2-3 编写函数htoi(s),把由16进制数字组成的字符串(包含可选的前缀0X或0x)转换成与之等价的 ...

  2. 【基础】excel如何根据数据内容显示不同颜色。

    需求: 店柜完成率排名相比上阶段升降,升显示绿色“↑“,降显示红色“↓”,持平显示黑色“-”. 步骤: 第一步 先计算两次排名的差值(本次排名-上次排名). 第二步 对差值列设置单元格格式,设置格式如 ...

  3. windows假死原因调查

    0. 现象 windows假死了,键盘功能正常,就是画面卡住不动了. 1. 看log linux下面很容易通过命令dmesg和/var/log/message来看日志. 但是windows就懵逼了,不 ...

  4. 微信小程序-视频弹幕的项目

    1.视频播放器 2.选择弹幕颜色 3.弹幕来了... 一般微信小程序需要配置.wxml.wxss.js.json文件,所有接下来也是要配置这几个文件,请看下图: 第一:  index.wxml < ...

  5. php连接数据库 需要下载adodb

    <?include('adodb/ADOdb.inc.php'); # 加载ADODB$conn = &ADONewConnection('odbc_mssql'); # 建立一个连结$ ...

  6. CF861D

    题目链接:http://codeforces.com/contest/861/problem/D 解题思路: 优雅的暴力. 对于输入的每一个号码,从短到长找出它的所有子串,用 vector 保存每个号 ...

  7. 查找最大元素(hdu2025)

    输入方式:直接循环输入不带空格的未知长度的字符串. 思考:直接循环输入未知长度的字符串,用while(gets_s()),循环内外不用getchar().(注意,每次字符串都是以整体输入) #incl ...

  8. 填坑!线上Presto查询Hudi表异常排查

    1. 引入 线上用户反馈使用Presto查询Hudi表出现错误,而将Hudi表的文件单独创建parquet类型表时查询无任何问题,关键报错信息如下 40931f6e-3422-4ffd-a692-6c ...

  9. python 读取txt文件

    1.打开文件 #1)1 f = open("test.txt","r") #设置文件对象 f.close() #关闭文件 #2) #为了方便,避免忘记close ...

  10. Linux退出vi编辑

    按ESC键 跳出vi的编辑命令,然后: :w 保存文件但不退出vi:w file 将修改另外保存到file中,不退出vi:w! 强制保存,不推出vi:wq 保存文件并退出vi:wq! 强制保存文件,并 ...