Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

184
Visualizações
How do I reduce the max size of a file upload for a multi part section in .net?

I am using code from the .net samples on streaming file uploads:

    [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.");
    }

But the problem is I am able to upload a 20MB PDF. I want to reduce this to 5MB. Ideally I want to be able to set this per file extension.

The documentation I have read suggests adding this to my Startup:

        var tenMB = 10485760;
        services.Configure<FormOptions>(options =>
        {
            options.MultipartBodyLengthLimit = tenMB;
        });

As I understand this is supposed to throw an invalid data exception, but it doesnt. It doesnt do anything.

What am I doing wrong here please? I dont think I can read the size of a stream without reading the stream into memory?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

I believe the only way to do this is at the time of reading the stream. I achieved this with a buffer to improve performance (less reads) and a running count for how many bytes have been moved from the TCP stream to the file system. If it becomes too large the stream stops and the partial upload is deleted from the file system.

        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 Relatório

0

insert this in Startup class or it will not work otherwise

public void ConfigureServices(IServiceCollection services)
{
        services.AddMvc();
        services.Configure<FormOptions>(options => {
            options.ValueLengthLimit = tenMB;
            options.MultipartBodyLengthLimit = tenMB;
        })
 }
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda