Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

182
Vistas
¿Cómo reduzco el tamaño máximo de carga de un archivo para una sección de varias partes en .net?

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.

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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); }
over 4 years ago · Santiago Trujillo Denunciar

0

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; }) }
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda