netcore文件上传两种方式

  netcore官方给出的两种文件上传方式分别为“缓冲”、“流式”。我简单的说说两种的区别,

  1.缓冲:通过模型绑定先把整个文件保存到内存,然后我们通过iformfile得到stream,优点是效率高,缺点对内存要求大。文件不宜过大。

  2.流式处理:直接读取请求体装载后的section 对应的stream 直接操作strem即可。无需把整个请求体读入内存,

以下为官方微软说法

缓冲

  整个文件读入 iformfile,它是文件的 c# 表示形式,用于处理或保存文件。 文件上传所用的资源(磁盘、内存)取决于并发文件上传的数量和大小。 如果应用尝试缓冲过多上传,站点就会在内存或磁盘空间不足时崩溃。 如果文件上传的大小或频率会消耗应用资源,请使用流式传输。

流式处理   

  从多部分请求收到文件,然后应用直接处理或保存它。 流式传输无法显著提高性能。 流式传输可降低上传文件时对内存或磁盘空间的需求。

文件大小限制

  说起大小限制,我们得从两方面入手,1应用服务器kestrel 2.应用程序(我们的netcore程序),

1.应用服务器kestre设置

  应用服务器kestrel对我们的限制主要是对整个请求体大小的限制通过如下配置可以进行设置(program -> createhostbuilder),超出设置范围会报 badhttprequestexception: request body too large 异常信息

public static ihostbuilder createhostbuilder(string[] args) =>
           host.createdefaultbuilder(args)
               .configurewebhostdefaults(webbuilder =>
               {
                   webbuilder.configurekestrel((context, options) =>
                   {
                       //设置应用服务器kestrel请求体最大为50mb
                       options.limits.maxrequestbodysize = 52428800;
                   });
                   webbuilder.usestartup<startup>();
});

2.应用程序设置

  应用程序设置 (startup->  configureservices) 超出设置范围会报invaliddataexception 异常信息

services.configure<formoptions>(options =>
 {
             options.multipartbodylengthlimit = long.maxvalue;
 });

通过设置即重置文件上传的大小限制。

源码分析

  这里我主要说一下 multipartbodylengthlimit  这个参数他主要限制我们使用“缓冲”形式上传文件时每个的长度。为什么说是缓冲形式中,是因为我们缓冲形式在读取上传文件用的帮助类为 multipartreaderstream 类下的 read 方法,此方法在每读取一次后会更新下读入的总byte数量,当超过此数量时会抛出  throw new invaliddataexception($multipart body length limit {lengthlimit.getvalueordefault()} exceeded.);  主要体现在 updateposition 方法对 _observedlength  的判断

以下为 multipartreaderstream 类两个方法的源代码,为方便阅读,我已精简掉部分代码

read

public override int read(byte[] buffer, int offset, int count)
 {
          
          var buffereddata = _innerstream.buffereddata;
      int read;
      read = _innerstream.read(buffer, offset, math.min(count, buffereddata.count));
          return updateposition(read);
}

updateposition

private int updateposition(int read)
        {
            _position += read;
            if (_observedlength < _position)
            {
                _observedlength = _position;
                if (lengthlimit.hasvalue && _observedlength > lengthlimit.getvalueordefault())
                {
                    throw new invaliddataexception($"multipart body length limit {lengthlimit.getvalueordefault()} exceeded.");
                }
            }
            return read;
}

通过代码我们可以看到 当你做了 multipartbodylengthlimit 的限制后,在每次读取后会累计读取的总量,当读取总量超出

 multipartbodylengthlimit  设定值会抛出 invaliddataexception 异常,

最终我的文件上传controller如下

  需要注意的是我们创建 multipartreader 时并未设置 bodylengthlimit  (这参数会传给 multipartreaderstream.lengthlimit )也就是我们最终的限制,这里我未设置值也就无限制,可以通过 updateposition 方法体现出来

using microsoft.aspnetcore.http;
using microsoft.aspnetcore.mvc;
using microsoft.aspnetcore.webutilities;
using microsoft.net.http.headers;
using system.io;
using system.threading.tasks;
 
namespace bigfilesupload.controllers
{
    [route("api/[controller]")]
    public class filecontroller : controller
    {
        private readonly string _targetfilepath = "c:\\files\\tempdir";
 
        /// <summary>
        /// 流式文件上传
        /// </summary>
        /// <returns></returns>
        [httppost("uploadingstream")]
        public async task<iactionresult> uploadingstream()
        {
 
            //获取boundary
            var boundary = headerutilities.removequotes(mediatypeheadervalue.parse(request.contenttype).boundary).value;
            //得到reader
            var reader = new multipartreader(boundary, httpcontext.request.body);
            //{ bodylengthlimit = 2000 };//
            var section = await reader.readnextsectionasync();
 
            //读取section
            while (section != null)
            {
                var hascontentdispositionheader = contentdispositionheadervalue.tryparse(section.contentdisposition, out var contentdisposition);
                if (hascontentdispositionheader)
                {
                    var trustedfilenameforfilestorage = path.getrandomfilename();
                    await writefileasync(section.body, path.combine(_targetfilepath, trustedfilenameforfilestorage));
                }
                section = await reader.readnextsectionasync();
            }
            return created(nameof(filecontroller), null);
        }
 
        /// <summary>
        /// 缓存式文件上传
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        [httppost("uploadingformfile")]
        public async task<iactionresult> uploadingformfile(iformfile file)
        {
            using (var stream = file.openreadstream())
            {
                var trustedfilenameforfilestorage = path.getrandomfilename();
                await writefileasync(stream, path.combine(_targetfilepath, trustedfilenameforfilestorage));
            }
            return created(nameof(filecontroller), null);
        }
 
 
        /// <summary>
        /// 写文件导到磁盘
        /// </summary>
        /// <param name="stream">流</param>
        /// <param name="path">文件保存路径</param>
        /// <returns></returns>
        public static async task<int> writefileasync(system.io.stream stream, string path)
        {
            const int file_write_size = 84975;//写出缓冲区大小
            int writecount = 0;
            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 = 0;
                while ((readcount = await stream.readasync(bytearr, 0, bytearr.length)) > 0)
                {
                    await filestream.writeasync(bytearr, 0, readcount);
                    writecount += readcount;
                }
            }
            return writecount;
        }
 
    }
}

 

 总结:

如果你部署 在iis上或者nginx 等其他应用服务器 也是需要注意的事情,因为他们本身也有对请求体的限制,还有值得注意的就是我们在创建文件流对象时 缓冲区的大小尽量不要超过netcore大对象的限制。这样在并发高的时候很容易触发二代gc的回收.