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. F - Qualification Rounds CodeForces - 868C 二进制

    F - Qualification Rounds CodeForces - 868C 这个题目不会,上网查了一下,发现一个结论就是如果是可以的,那么两个肯定可以满足. 然后就用二进制来压一下这个状态就 ...

  2. SpringData Redis的简单使用

    SpringDate Redis是在Jedis框架的基础之上对Redis进行了高度封装,通过简单的属性配置就可以通过调用方法完成对Redis数据库的操作,而且SpringData Redis使用了连接 ...

  3. jQuery的相关尺寸获取 - 学习笔记

    获取元素相对于文档的偏移量 获取当前元素相对于父级元素的偏移量 获取文档滚动距离 获取元素的宽度和高度 设置元素的宽度和高度 获取可视区域的宽度和高度 获取文档的宽度和高度 获取元素相对于文档的偏移量 ...

  4. 网上流行护眼色的RGB值和颜色代码

    网上流行护眼色的RGB值和颜色代码   绿豆沙色能有效的减轻长时间用电脑的用眼疲劳!色调:85,饱和度:123,亮度:205: RGB颜色红:199,绿:237,蓝:204:十六进制颜色:#C7EDC ...

  5. 图形学_Bezier曲线

    Bezier曲线由n个控制点生成,举个例子:当n=2时,点$P_0$.$P_1$之间遵从计算: $P_0=(1-t)P_0+tP_1$ 而推广为n维时,有: $P^n_0=(1-t)P^{n-1}_0 ...

  6. 单片机P0口

    http://www.21ic.com/app/mcu/201307/186301.htm http://blog.csdn.net/zmq5411/article/details/6005977 h ...

  7. tp5参数传入

    把应用配置文件中的url_param_type参数的值修改如下: // 按照参数顺序获取 'url_param_type' => 1, 现在,URL的参数传值方式就变成了严格按照操作方法的变量定 ...

  8. POI 导入excel数据自动封装成model对象--代码

    所有的代码如下: import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; ...

  9. (Python基础教程之十三)Python中使用httplib2 – HTTP GET和POST示例

    Python基础教程 在SublimeEditor中配置Python环境 Python代码中添加注释 Python中的变量的使用 Python中的数据类型 Python中的关键字 Python字符串操 ...

  10. 「雕爷学编程」Arduino动手做(8)——湿度传感器模块

    37款传感器和模块的提法,在网络上广泛流传,其实Arduino能够兼容的传感器模块肯定是不止37种的.鉴于本人手头积累了一些传感器与模块,依照实践出真知(动手试试)的理念,以学习和交流为目的,这里准备 ...