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. 解决php获取不到Authorization问题

    我用的是thinkphp3.2.3, 在使用jwt的时候通过Authorization传递token,但是每次都接收不到,通过修改..htaccess文件,问题成功解决了,下面是的.htaccess文 ...

  2. 初识Matlab及界面认识

    通过本章节的学习,需要掌握: MATLAB语言是什么 MATLAB在互联网语言中地位与应用 目标:利用MATLAB进行问题求解的基本规律.够使用MATLAB作为专业应用的工具. 1.什么叫计算? (1 ...

  3. 使用Pandas读取CSV文件

    使用Pandas读取CSV文件 import pandas as pd csv_data = pd.read_csv('birth_weight.csv') # 读取训练数据 print(csv_da ...

  4. Android Bluetooth How To--Based on Android L Bluedroid

    Android Bluetooth How To(Based on Android L Bluedroid) 持续更新中… 1.How to enable btsnoop log? a) UI Set ...

  5. [hdu5379 Mahjong tree]dfs计数

    题意:给n个节点的树编号1-n,一个节点唯一对应一种编号,要求编完号的树满足如下性质:所有节点的儿子的编号是连续的,对一棵子树,它包含的所有节点的编号也是连续的.连续的意思是把所有数排序后是一段连续的 ...

  6. springMVC的自定义annotation(@Retention@Target)详解

    自定义注解: 使用@interface自定义注解时,自动继承了java.lang.annotation.Annotation接口,由编译程序自动完成其他细节.在定义注解时,不能继承其他的注解或接口.@ ...

  7. 给bootstrap右边的菜单加上右键关闭

    <ul class="rightmenu"> <li data-type="closethis">关闭当前</li> < ...

  8. JAVA异常以及字节流

    异常 JAVA异常可以分为编译时候出现的异常和执行时候出现的异常 JVM默认处理异常的方法是抛出异常 异常处理 //第一种 try{ 可能会出错的代码 }catch{ 发生异常后处置方法 }final ...

  9. Rabbitmq 整合Spring,SpringBoot与Docker

    SpringBootLearning是对Springboot与其他框架学习与研究项目,是根据实际项目的形式对进行配置与处理,欢迎star与fork. [oschina 地址] http://git.o ...

  10. Handler Looper MessageQueue 之间的关系

    Handler Looper MessageQueue 之间的关系 handler在安卓开发中常用于更新界面ui,以及其他在主线程中的操作.内部结构大概图为: 1.handler持有一个Looper对 ...