How to fix error in file upload?

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, it generates the image error below .

The goal is to only allow upload .csv files, but I can not let problems happen like this. Can anyone help me?

    
asked by anonymous 10.06.2015 / 17:01

3 answers

3

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

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

I think this is an absurd value, I suggest setting it up according to your needs. In fact, I think the default value is appropriate for what you are trying to do. Try to validate the file size before sending it to the server so that no such error occurs.

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 if the size is greater than 29.999.999 bytes it prevents the continuation (instead of the alert do the appropriate treatment).

    
10.06.2015 / 17:39
0

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

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><scriptsrc="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script><formid="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>
    
10.06.2015 / 17:18
0

The error occurs because your file is larger than 4 megabytes ( is the default configuration of IIS ). Set up your Web.config file 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>

It is important to say that maxRequestLength is in KBytes, and maxAllowedContentLength in bytes. Both are equivalent to 1 Gb.

    
10.06.2015 / 17:41