访问Request.Form.Files会抛出异常System.io.InvalidDataException

时间:2017-11-18 04:36:18

标签: c# jquery asp.net-core-mvc asp.net-core-2.0 summernote

正如我的标题中所提到的,在访问Request.Form.Files时,应用程序抛出异常

System.Io.InvalidDataException: "Multipart body length limit 16384 exceeded" in an Asp.Net Core 2.0.0 Web Application.我正在处理的应用程序是Asp.Net核心MVC Web应用程序。我使用Summernote作为我的WYSIWYG文本编辑器。在那里我启用了功能上传图像(s。我的Javascript)。这很好,直到我需要实现另一个上传器来上传像.pdf,txt,doc这样的文本文件。 使用summernote texteditor时出现错误,使用“标准”上传按钮或自定义pdf上传按钮(s.C#代码)。 Image功能正常,直到我(尝试)实现新的pdf文件上传器。起初我的错误看起来非常基本,因为很明显,我试图上传的文件大于16kb(Asp.Net Cores Uploadlimit),所以我尝试了“常用”方法(s。下面)修复此错误,可以在Stack Overflow和类似网站上找到:

    services.Configure<FormOptions>(x =>
    {
        x.ValueLengthLimit = int.MaxValue;
        x.MultipartBodyLengthLimit = long.MaxValue;
        x.MemoryBufferThreshold = 20;
    });

public class RequestFormSizeLimitAttribute : Attribute, IAuthorizationFilter, IOrderedFilter
{
    public int Order { get; }
    private readonly FormOptions _formOptions;

    public RequestFormSizeLimitAttribute(int valueCountLimit)
    {
        _formOptions = new FormOptions()
        {

            ValueCountLimit = valueCountLimit,
            KeyLengthLimit = valueCountLimit
        };
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var features = context.HttpContext.Features;
        var formFeature = features.Get<IFormFeature>();

        if (formFeature == null || formFeature.Form == null)
        {
            // Request form has not been read yet, so set the limits
            features.Set(new FormFeature(context.HttpContext.Request, _formOptions));
        }
    }


}

<system.web>
    <httpRuntime maxRequestLength="1048576" />
  </system.web>
  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
    </security>
  </system.webServer>

然而,这些方法都没有修复我的错误。 首先是我的Jquery代码:

//For Image Uploading
function sendFiles(file) {
    var data = new FormData();
    data.append("file", file);
    data.append('divisionId', $('#divisionId').val());
    $.ajax({
        data: data,
        type: "POST",
        url: "/api/File/UploadImageAjax",
        cache: false,
        contentType: false,
        processData: false,
        success: function (image) {
            if (image !== "Error") {
                var picture = $(image);
                $('#summernote').summernote("insertNode", picture[0]);
            } else {
                bootbox.alert("Fehler beim hochladen des Bildes.");
            }
        }
    });
}

//For PDF-File Upload
$('#btnUpload').on('click', function (e) {
        var validation = validator.form();
        e.preventDefault();
        if (validation) {
            var data = new FormData();
            var text = document.getElementById('pdfText').value;
            var fileSelect = document.getElementById('pdfFile');
            data.append('linkName', text);
            data.append('divisionId', $('#divisionId').val());
            var files = fileSelect.files;
            data.append('file', files[0]);
            closeModal();
            $.ajax({
                data: data,
                type: "POST",
                url: "/api/File/UploadTextFileAjax",
                cache: false,
                contentType: false,
                processData: false,
                success: function (file) {
                    var atag = document.createElement('a');
                    atag.setAttribute('href', file.absoulutePath);
                    atag.setAttribute('id', file.fileId);
                    atag.innerHtml = file.linkText;
                    $('#summernote').summernote('insertNode', atag);
                },
                error: function(respons) {
                    bootbox.alert("Fehler beim Speichern der Text Datei.");
                }
            });

        }
    });

最后来自Controller的C#代码:

[HttpPost]
        [RequestFormSizeLimit(valueCountLimit: 2147483647)]
        public async Task<IActionResult> UploadImageAjax()
        {
            //Exception thrown here.
            var files = Request.Form.Files;
            var request = Request.Form.FirstOrDefault(d => d.Key == "divisionId");
            var divisionName = await GetDivisionNameAsync(request);
            if (divisionName != null)
            {
                var user = await _userManager.GetUserAsync(HttpContext.User);
                if (files.Count == 1 && user != null)
                {
                    for (int i = 0; i < 1; i++)
                    {
                        var file = files[i];
                        if (TestImageFileName(file))
                        {
                            var path = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.ToString().Trim('"');
                            var fileName = $@"\images\Sportarten\{divisionName}\{path}";
                            if (!await _imageHandler.IsImageInDbAsync(fileName))
                            {
                                path = _hosting.WebRootPath + fileName;
                                using (FileStream fs = System.IO.File.Create(path))
                                {
                                    await file.CopyToAsync(fs);
                                    await fs.FlushAsync();
                                }
                                var image = new ImageViewModel { FileName = file.FileName, AbsolutePath = fileName, AspNetUserId = user.Id, FullPath = path };
                                var imageId = await _imageHandler.AddImageAsync(image);
                                var imageNode = $@"<img id='{imageId}' src='{fileName}' class='img-responsive'/>";
                                return Json(imageNode);
                            }
                            var id = await _imageHandler.GetImageIdbyNameAsync(path);
                            var node = $@"<img id='{id}' src='{fileName}' class='img-responsive'/>";
                            return Json(node);

                        }
                    }
                }
            }

            return BadRequest("Error");
        }

    [HttpPost]
    public async Task<IActionResult> UploadTextFileAjax()
    {
        //Exception thrown here.
        var files = Request.Form.Files;
        var request = Request.Form.FirstOrDefault(d => d.Key == "divisionId");
        var divisionName = await GetDivisionNameAsync(request);
        var linkText = Request.Form.FirstOrDefault(l => l.Key == "linkName").Value.ToString();
        if (linkText != null && divisionName != null)
        {
            var user = await _userManager.GetUserAsync(HttpContext.User);
            if (files.Count == 1 && user != null)
            {
                for (int i = 0; i < 1; i++)
                {
                    var file = files[i];
                    if (TestTextFileName(file))
                    {
                        var path = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.ToString().Trim('"');
                        var fileName = $@"\files\Sportarten\{divisionName}\{path}";
                        if (await _file.IsFileInDb(fileName))
                        {
                            path = _hosting.WebRootPath + fileName;
                            using (FileStream fs = System.IO.File.Create(path))
                            {
                                await file.CopyToAsync(fs);
                                await fs.FlushAsync();
                            }
                            var textFile = new FileViewModel
                            {
                                AbsolutePath = fileName,
                                AspNetUserId = user.Id,
                                FileName = file.FileName,
                                FullPath = path
                            };
                            var fileId = await _file.AddFile(textFile);
                            return Ok(new {absolutePath = path, fileId = fileId, linkText = linkText});
                        }
                        var oldText = await _file.FindFilebyName(path);
                        return Ok(new { absolutePath = oldText.AbsolutePath, fileId = oldText.FileId, linkText = linkText });
                    }

                }
            }
        }
        return BadRequest("Error");
    }  

最后这是我得到的Stacktrace,当错误被抛出时(抱歉质量不好): Full Stacktrace of Error

0 个答案:

没有答案