Estoy usando el código de las muestras de .net en las cargas de archivos de transmisión:
[HttpPost] public async Task<IActionResult> Post() { var request = HttpContext.Request; // validation of Content-Type // 1. first, it must be a form-data request // 2. a boundary should be found in the Content-Type if (!request.HasFormContentType || !MediaTypeHeaderValue.TryParse(request.ContentType, out var mediaTypeHeader) || string.IsNullOrEmpty(mediaTypeHeader.Boundary.Value)) { return new UnsupportedMediaTypeResult(); } var reader = new MultipartReader(mediaTypeHeader.Boundary.Value, request.Body); var section = await reader.ReadNextSectionAsync(); // This sample try to get the first file from request and save it // Make changes according to your needs in actual use while (section != null) { var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition); if (hasContentDispositionHeader && contentDisposition.DispositionType.Equals("form-data") && !string.IsNullOrEmpty(contentDisposition.FileName.Value)) { await _uploader.UploadAsync(section.Body); return Ok(); } section = await reader.ReadNextSectionAsync(); } // If the code runs to this location, it means that no files have been saved return BadRequest("No files data in the request."); }Pero el problema es que puedo cargar un PDF de 20 MB. Quiero reducir esto a 5 MB. Idealmente, quiero poder configurar esto por extensión de archivo.
La documentación que he leído sugiere agregar esto a mi Inicio:
var tenMB = 10485760; services.Configure<FormOptions>(options => { options.MultipartBodyLengthLimit = tenMB; });Según tengo entendido, se supone que esto arroja una excepción de datos no válidos, pero no es así. No hace nada.
¿Qué estoy haciendo mal aquí, por favor? No creo que pueda leer el tamaño de un flujo sin leer el flujo en la memoria.
Creo que la única manera de hacer esto es al momento de leer la transmisión. Logré esto con un búfer para mejorar el rendimiento (menos lecturas) y un conteo continuo de cuántos bytes se han movido de la secuencia TCP al sistema de archivos. Si se vuelve demasiado grande, la transmisión se detiene y la carga parcial se elimina del sistema de archivos.
var maxFileSizeBytes = _settings.MaxUploadSize; long totalBytesRead = 0; while (true) { byte[] buffer = new byte[Kilobytes.Eight]; int bytesRead = await inputStream.ReadAsync(buffer, 0, buffer.Length); if (bytesRead == 0) break; totalBytesRead += bytesRead; if (totalBytesRead > maxFileSizeBytes) { DeleteFile(fileName, outputStream); throw UploadRejectedException.FileTooLarge(maxFileSizeBytes); } await outputStream.WriteAsync(buffer, 0, bytesRead); }inserte esto en la clase de inicio o no funcionará de otra manera
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.Configure<FormOptions>(options => { options.ValueLengthLimit = tenMB; options.MultipartBodyLengthLimit = tenMB; }) }