How to Fix File Upload Error?

Asked

Viewed 1,950 times

3

I have the following form:

@using (Html.BeginForm("importCSV", "Administrador", FormMethod.Post, new { @id = "upldFrm", @enctype = "multipart/form-data" }))
        {
            <input id="file" name="file" type="file" />
            <label style="color:red; white-space: pre-line">@ViewBag.Message</label>
        }

<script>
        $(function () {
            $("#file").change(function () {
                $("#upldFrm").submit();
            });
        });
    </script>

When I send any file (.csv, .jpg, .txt, and others) it works perfectly, but when I try to send a file like: Arquivo 16.03.15.rar it does not even arrive in the action, generates the error of the image below. inserir a descrição da imagem aqui

The goal is to allow only uploading files .csv, but I can’t let problems like this happen. Someone can help me?

  • When you say "not even in Action", what exactly happens?

  • I updated the question my friend... Well, I put a breakpoint in the action he is calling, and when I send a file . csv for example, it gets there, but when I send such quoted file, the error is generated without even getting into the action.

  • Apparently the error is when it sends a very large file, regardless of the extension

3 answers

3


You have to increase the maximum size of the request, through the property maxAllowedContentLength. Probably your . rar is exceeding the standard size which is 30.000.000 bytes (approx. 30MB):

<system.web>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="2147483647" />
      </requestFiltering>
    </security>
    ...
</system.web>

2147483647 bytes = 2GB

I believe this is an absurd value, I suggest you configure according to your needs. In fact, I think the default value is appropriate for what you’re trying to do. Try to validate the file size before sending to the server to avoid such error.

You can do this validation with jQuery as follows:

$('#meu-input-upload').bind('change', function() {  
    var tamanho_maximo = 29999999;
    if(this.files[0].size > 29999999) {
        alert("Tamanho máximo excedido");
        this.value = "";
    }
});

In case the size is larger than 29.999.999 bytes prevents continuation (in place of Alert do the proper treatment).

  • 2

    Just to know the value of 2147483647 equals to 2GB.

0

You have to use an extension check of the files that will be sent, in case only files that have the extension .csv.

Example:

function comprova_extensao(formulario, arquivo) {
  extensoes_permitidas = new Array(".csv");
  meuerro = "";
  if (!arquivo) {
    //Se não tenho arquivo, é porque não se selecionou um arquivo no formulário.
    meuerro = "Não foi selecionado nenhum arquivo";
  } else {
    //recupero a extensão deste nome de arquivo
    extensao = (arquivo.substring(arquivo.lastIndexOf("."))).toLowerCase();
    //alert (extensao);
    //comprovo se a extensão está entre as permitidas
    permitida = false;
    for (var i = 0; i < extensoes_permitidas.length; i++) {
      if (extensoes_permitidas[i] == extensao) {
        permitida = true;
        break;
      }
    }
    if (!permitida) {
      meuerro = "Comprova a extensão dos arquivos a subir. \nSó se podem subir arquivos com extensões: " + extensoes_permitidas.join();
    } else {
      //submeto!
      alert("Tudo correto. Vou submeter o formulário.");
      formulario.submit();
      return 1;
    }
  }
  //se estou aqui é porque não se pode submeter
  alert(meuerro);
  return 0;
}
<form method=post action="#" enctype="multipart/form-data">
  <input type=file name="arquivoupload">
  <input type=button name="Submit" value="Enviar" onclick="comprova_extensao(this.form, this.form.arquivoupload.value)">
</form>

If you prefer to use jQuery:

jQuery.validator.setDefaults({
  debug: true,
  success: "valid"
});
$("#myform").validate({
  rules: {
    field: {
      required: true,
      extension: "csv"
    }
  }
});
<script src="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
<script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<form id="myform">
  <label for="field">Apenas arquivos no formato .csv</label>
  <input type="file" class="left" id="field" name="field">
  <br/>
  <input type="submit" value="Validate!">
</form>

  • 1

    Despite treating the extension, the user can simply change the name of the extension and send the wrong content anyway.

  • 1

    Trade example .rar for .csv and send.

0

Error occurs because your file is more than 4 megabytes (is the default IIS configuration). Configure your file Web.config with the following:

<configuration>
  ...
  <system.web>
    ...
    <!-- Aqui configuro apenas o tamanho da requisição como um todo, e não exatamente o tamanho do anexo -->
    <httpRuntime maxRequestLength="1048576" />
    ...
  </system.web>
  ...
 <!-- Para o IIS 7 ou superior, também é preciso especificamente configurar o tamanho máximo do arquivo -->
 <system.webServer>
   ...
   <security>
      <requestFiltering>
         <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
   </security>
   ...
 </system.webServer>
 ...
</configuration>

Important to say that maxRequestLength is in Kbytes, and maxAllowedContentLength in bytes. Both equate to 1 Gb.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.