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. JAVA基础篇 之 方法的重载

    ​ 任何程序语言都具备了一项重要的特性就是对名字的运用.当创建一个对象时,也就给此对象分配到的存储空间取了一个名字.所谓方法则是给某个动作取的名字.通过使用名字你可以引用所有的对象和方法. ​ 将人类 ...

  2. 【Spark】RDD的依赖关系和缓存相关知识点

    文章目录 RDD的依赖关系 宽依赖 窄依赖 血统 RDD缓存 概述 缓存方式 RDD的依赖关系 RDD和它依赖的父RDD的关系有两种不同的类型,即窄依赖(narrow dependency) 和宽依赖 ...

  3. Vulnhb 靶场系列:Jarbas1.0

    靶场镜像 官网 信息收集 攻击机kali IP地址 通过nmap 进行主机发现,发现目标机IP地址 nmap -sP 192.168.227.1/24 参数说明: -sP (Ping扫描) 该选项告诉 ...

  4. 设计模式之GOF23建造者模式

    组件很多,装配顺序不定 本质: 1,分离了对象子组件的单独构造(Builder负责)和装配(Director负责),从而可以构造出复杂的对象,这个模式适用于某个对象的构建过程复杂的情况下使用 2,实现 ...

  5. angular js 页面修改数据存入数据库

    一.编写service,修改数据要根据ID回显数据 //根据ID查询 public Brand findById(Long id); //修改 public int update(Brand bran ...

  6. tp5参数传入

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

  7. chmod的用法

    指令名称 : chmod 使用权限 : 所有使用者 使用方式 : chmod [-cfvR] [--help] [--version] mode file... 说明 : Linux/Unix 的档案 ...

  8. Amaze UI学习笔记——JS学习历程一

    1.自定义事件 (1)一些组件提供了自定义事件,命名方式为{事件名称}.{组件名称}.amui,用户可以查看组件文档了解.使用这些事件,如: $('#myAlert').on('close.alert ...

  9. vim命令备份

    vim命令 vim键盘位置说明 在命令状态下对当前行用 == (连按=两次), 或对多行用 n==(n是自然数)表示自动缩进从当前行起的下面n行. 可以试试把代码缩进任意打乱再用 n== 排版,相当于 ...

  10. React实践相关

    语法高亮: sublime ctrl+shift+P 安装babel ,在view-syntax-open all width current extension as...-babel-js(bab ...