.NetCore 上传文件 解除大文件限制

本文介绍如何使用ASP.NET Core配置无限大的文件上传限制,并通过WebUploader实现文件的选择、上传及验证过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.设置允许无限大

public class Program
{
 public static void Main(string[] args)
 {
     
     CreateWebHostBuilder(args).Build().Run();
 }

 public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
     WebHost.CreateDefaultBuilder(args)
     .UseUrls(new string[]{"http://*:8081","https://*:8082"})
     .UseStartup<Startup>().UseKestrel(options =>
     {
         //控制中间件允许的上传文件大小为:不限制
         options.Limits.MaxRequestBodySize = null;
     });

}

2.上传接口与验证接口


 /// <summary>
 /// 上传文件
 /// </summary>
 /// <returns></returns>
 [HttpPost]
 public ActionResult UploadFile(string uId)
 {
     string basePath = $"{Tools.basePath}\\";
    
     //string name = Request.Query["address"];
     string imgPath = $"{basePath}";
     string dicPath = imgPath;
     if (!Directory.Exists(dicPath))
     {
         Directory.CreateDirectory(dicPath);
     }
     var img = Request.Form.Files[0];
     if (img == null)
     {
         return Content("上传失败");
     }
     
    
     string fileName = "uId"+uId.ToString()+"_"+$"{DateTime.Now.ToString("yyyy_MM_dd[HH-mm]")}_"+ img.FileName;//Guid.NewGuid().ToString() + ext;
     string filePath = Path.Combine(dicPath, fileName);
     if (System.IO.File.Exists(filePath))
     {
         System.IO.File.Delete(filePath);
     }
     using (FileStream fs = System.IO.File.Create(filePath))
     {
         img.CopyTo(fs);
         fs.Flush();
     }
     return Json(new { file_Name = fileName });

 }

 /// <summary>
 /// webUpLoader验证文件上传成功
 /// </summary>
 /// <param name="filename"></param>
 /// <param name="uId"></param>
 /// <returns></returns>
 [HttpPost]
 public IActionResult Success(string filename,string uId)
 {
     
     string basePath = $"{Tools.basePath}\\";
     string imgPath = $"{basePath}";
     if (!Directory.Exists(imgPath))
     {
         Response.StatusCode = 400;
         return Json(new { state = "eroor" });
     }
     imgPath += "uId" + uId.ToString() + "_" + $"{DateTime.Now.ToString("yyyy_MM_dd[HH-mm]")}_" + filename;
     if (!System.IO.File.Exists(imgPath))
     {
         Response.StatusCode = 400;
         return Json(new { state = "eroor" });
     }
     Response.StatusCode = 200;
     return Json(new { state = "success" });

 }

3.网页代码


@{
    ViewData["Title"] = "Submit";
}

<link rel="stylesheet" type="text/css" href="https://cdn.bootcss.com/webuploader/0.1.1/webuploader.css">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="https://cdn.bootcss.com/webuploader/0.1.1/webuploader.js"></script>

<div>
    <h1>用户id: @ViewBag.uId</h1>
    <h1>您所要上传的文件是:</h1>  
    <div><span style="color:red">目前只支持PDF的打印</span></div>
</div>
<div id="uploader" class="wu-example">
    <!--用来存放文件信息-->
    <ul id="thelist" class="list-group"></ul>
    <div class="uploader-list"></div>
    <div class="btns">
        <div id="picker" style="float:left;">选择文件</div>
        <input id="ctlBtn" type="button" value="开始上传" class="btn btn-default" style="width:78px;height:37px;margin-left:10px;" />
    </div>
</div>

<script>
    $(function () {
        initUpload();
    })
    //初始化上传控件
    function initUpload() {
        var $ = jQuery;
        var $list = $('#thelist');
        var uploader = WebUploader.create({

            // 选完文件后,是否自动上传。
            auto: false,
            // swf文件路径
            swf: 'https://cdn.bootcss.com/webuploader/0.1.1/Uploader.swf',

            // 文件接收服务端。
            server: encodeURI('UploadFile?' +'uId=@ViewBag.uId'),  //+'&course_name='+'ViewBag.course_name'

            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建,可能是input元素,也可能是flash.
            pick: '#picker',

            multiple: false, // 选择多个
            chunked: false,// 开起分片上传。
            threads: 1, // 上传并发数。允许同时最大上传进程数。

            // 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传!
            resize: false
        });
        // 当有文件被添加进队列的时候
        uploader.on('fileQueued', function (file) {
            $list.append('<li id="' + file.id + '" class="list-group-item">' +
                '<span class="fileName" dataValue="">' + file.name + '</span>' +
                '<span class="state" style=\" margin-left: 10px;\">等待上传</span>' +
                '<span class="filepath" dataValue="0" style=\" margin-left: 10px;display: none;\"></span>' +
                '<span class="download" style="margin-left:20px;"></span>' +
                '<span class="webuploadDelbtn"style=\"float: right;display: none; \">删除<span>' +
                '</li>');
        });
        // 文件上传过程中创建进度条实时显示。
        uploader.on('uploadProgress', function (file, percentage) {
            var $li = $('#' + file.id),
                $percent = $li.find('.progress .progress-bar');

            // 避免重复创建
            if (!$percent.length) {
                $percent = $('<div class="progress progress-striped active">' +
                    '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                    '</div>' +
                    '</div>').appendTo($li).find('.progress-bar');
            }

            $li.find('span.state').text('上传中');

            $percent.css('width', percentage * 100 + '%');

        });

        // 文件上传成功,给item添加成功class, 用样式标记上传成功。
        uploader.on('uploadSuccess', function (file, response) {
            var $li = $('#' + file.id);
            //$('#' + file.id).find('span.state').text('正在上传');
            $.post('Success', { fileName: file.name, uId:@ViewBag.uId }, function (data) {
                $li.find('span.state').html("上传成功");
                $li.find('span.filepath').attr("dataValue", 1);
                $li.find('span.fileName').attr("dataValue", data.filename);
                $li.find('span.fileName').html(data.filename);
                //$li.find('span.download').html("<a href=\"../../PublicInfoManage/Upload/DownFile?filePath=" + data.filepath + "&amp;fileName=" + data.filename + "\">下载</a>")
                //$li.find('span.webuploadDelbtn').show();
                $li.find('span.filepath').html(data.filepath);
                //增加列表存储
                files.push(data);
            }).fail(function () {
                $('#' + file.id).find('span.state').text("上传失败");
            });
        });

        // 文件上传失败,显示上传出错。
        uploader.on('uploadError', function (file, reason) {
            $('#' + file.id).find('p.state').text(reason);
        });

        // 完成上传完了,成功或者失败,先删除进度条。
        uploader.on('uploadComplete', function (file) {
            $('#' + file.id).find('.progress').fadeOut();
        });

        //所有文件上传完毕
        uploader.on("uploadFinished", function () {
            //提交表单

        });
        //开始上传
        $("#ctlBtn").click(function () {
            uploader.upload();

        });
        //删除
        $list.on("click", ".webuploadDelbtn", function () {
            debugger
            var $ele = $(this);
            var id = $ele.parent().attr("id");
            var file = uploader.getFile(id);
            uploader.removeFile(file);
            $ele.parent().remove();
            //移除数组
            var destFile = findFile(file.name)
            var index = files.indexOf(destFile);
            if (index > -1) {
                files.splice(index, 1);
            }
        });
    }


</script>
@*<script>


        $('#upload-container').click(function (event) {


            $("#picker").find('input').click();


        });

        var uploader = WebUploader.create({
            auto: true,// 选完文件后,是否自动上传。
            swf: 'https://cdn.bootcss.com/webuploader/0.1.1/Uploader.swf',// swf文件路径
            server: "Upload",// 文件接收服务端。
            dnd: '#upload-container',
            pick: '#picker',// 内部根据当前运行是创建,可能是input元素,也可能是flash. 这里是div的id
            fileNumLimit: 1,
            multiple: false, // 选择多个
            chunked: false,// 开起分片上传。
            threads: 1, // 上传并发数。允许同时最大上传进程数。
            method: 'POST', // 文件上传方式,POST或者GET。
            fileSizeLimit: 1024 * 1024 * 100 * 100, //验证文件总大小是否超出限制, 超出则不允许加入队列。
            fileSingleSizeLimit: 1024 * 1024 * 100, //验证单个文件大小是否超出限制, 超出则不允许加入队列。
            fileVal: 'file' // [默认值:'file'] 设置文件上传域的name。
        });

        uploader.on('fileQueued', function (file) {
            count++;
            // 选中文件时要做的事情,比如在页面中显示选中的文件并添加到文件列表,获取文件的大小,文件类型等
            console.log(file.ext);// 获取文件的后缀
            console.log(file.size);// 获取文件的大小
            console.log(file.name);
            var html = '<div class="upload-item"><span>上传的文件名:' + file.name + '</span><span data-file_id="' + file.id + '" class="btn-retry">重试</span><div class="percentage ' + file.id + '" style="width: 0%;"></div></div>';
            $('#upload-list').append(html);
        });

        uploader.on('uploadProgress', function (file, percentage) {
            console.log(percentage * 100 + '%');
            var width = $('.upload-item').width();
            $('.' + file.id).width(width * percentage);
        });

        uploader.on('uploadSuccess', function (file, response) {

            console.log(file.id + "传输成功");

            //alert(response.Path);
            layer.msg("文件上传成功~请点击转换按钮!");
            alreadyFileName = response.Path;
            fileTime = response.UpdataTime;
            $("#startConvert").attr("style", "display:block;");
        });

        uploader.on('uploadError', function (file) {
            console.log(file);
            console.log(file.id + 'upload error');
        });

        $('#upload-list').on('click', '.upload-item .btn-delete', function () {
            // 从文件队列中删除某个文件id
            file_id = $(this).data('file_id');
            // uploader.removeFile(file_id); // 标记文件状态为已取消
            uploader.removeFile(file_id, true); // 从queue中删除
            console.log(uploader.getFiles());
        });

        $('#upload-list').on('click', '.btn-retry', function () {
            uploader.retry($(this).data('file_id'));
        });

        uploader.on('uploadComplete', function (file) {
            console.log(uploader.getFiles());
        });
    </script>*@
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值