Usuário com melhor resposta
Limitar tamanho FileUpload

Pergunta
-
Bom dia, estou com um formulário para envio de email, onde o mesmo pode ser anexado um arquivo. Porém quando coloco um arquivo maior, ele me retorna o seguinte erro:
Tamanho máximo de solicitação excedido.
Gostaria de saber como posso fazer para tratar este erro, estou tentando fazer desta forma abaixo, porém continua caindo no erro:
if (Anexo.HasFile) { if (Anexo.FileBytes.Length <= 4096) { MemoryStream ms = new MemoryStream(Anexo.FileBytes); Attachment anexo = new Attachment(ms, Anexo.PostedFile.FileName); email.anexo = anexo; } else { ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Tamanho do arquivo excedido!');", true); } }
Obrigado!
- Editado Mariana C. Costa sexta-feira, 14 de julho de 2017 12:32
Respostas
-
Entendi, veja esse exemplo limitando ate 4MB, seu controle:
<asp:FileUpload ID="Anexo" runat="server" onchange="Javascript: VerificaTamanhoArquivo();" />
O Javascript:
function VerificaTamanhoArquivo() { var fi = document.getElementById('<%= Anexo.ClientID %>'); var maxFileSize = 4194304; // 4MB -> 4 * 1024 * 1024 if (fi.files.length > 0) { for (var i = 0; i <= fi.files.length - 1; i++) { var fsize = fi.files.item(i).size; if (fsize < maxFileSize) { alert("arquivo ok"); } else { alert("arquivo n permitido"); fi.value = null; } } } }
Isso resolve o problema.
- Marcado como Resposta Mariana C. Costa quinta-feira, 20 de julho de 2017 15:04
Todas as Respostas
-
Tentei fazer dessa forma em um exemplo que vi na net, porém não funcionou.
$(function () { $('<%= fileUploadCV.ClientID %>').change(function () { //because this is single file upload I use only first index var f = this.files[0] //here I CHECK if the FILE SIZE is bigger than 8 MB (numbers below are in bytes) if (f.size > 8388608 || f.fileSize > 8388608) { //show an alert to the user alert("Allowed file size exceeded. (Max. 8 MB)") //reset file upload control this.value = null; } }) });
-
Boa tarde, Mariana C. Costa.
Tudo bem? Obrigado por usar o fórum MSDN.
Continua dando o mesmo erro? Ou na segunda forma traz um erro diferente?
Atenciosamente,Filipe B de Castro
Esse conteúdo é fornecido sem garantias de qualquer tipo, seja expressa ou implícita
MSDN Community Support
Por favor, lembre-se de Marcar como Resposta as postagens que resolveram o seu problema. Essa é uma maneira comum de reconhecer aqueles que o ajudaram e fazer com que seja mais fácil para os outros visitantes encontrarem a resolução mais tarde.
-
-
Tentei fazer com validador, desta forma abaixo, porém também não funciona, cai direto no erro, e não no tratamento.
<asp:FileUpload ID="Anexo" runat="server" /> <asp:CustomValidator ID="NewPasswordCustomValidator" runat="server" Text="*" ToolTip="FileSize should not exceed 5kb" ErrorMessage="FileSize Exceeds the Limits.Please Try uploading smaller size files." ControlToValidate="Anexo" ClientValidationFunction="checkfilesize"></asp:CustomValidator> <asp:ValidationSummary ID="ValidationSummary1" runat="server" />
Code:
protected void checkfilesize(object source, ServerValidateEventArgs args) { string data = args.Value; args.IsValid = false; double filesize = Anexo.FileContent.Length; if (filesize > 5000) { args.IsValid = false; } else { args.IsValid = true; } }
-
-
Ainda não consegui resolver!
Boa tarde,
Configura no web.config:
<configuration> <system.web> <httpRuntime maxRequestLength="xxx" /> </system.web> </configuration>
Fonte: Upload Web Forms
-
-
Já fiz essa configuração, porém ele me retorna o mesmo erro:
Aquele seu javascript deve funcionar, a não ser que esse controle possua algum evento no code-behind... Possui algum evento o FileUpload ? Pq tem q verificar o tamanho antes de enviar ao servidor...Tamanho máximo de solicitação excedido.
Por isso preciso retornar a mensagem informando que o arquivo está com o tamanho excedido.
-
Tentei aquele javascript não sei pq não funcionou.. Estou fazendo a verificação pra não dar o erro, e também por ser enviado por email este arquivo, senão irá demorar muito para o envio, já que poderá ser enviado para uma lista.
Segue como está o fileUpload:
<asp:FileUpload ID="Anexo" runat="server" />
Tentei colocar esse código no code-behind qndo está enviando o email, mas não cai nele:
if (Anexo.HasFile) { HttpPostedFile file = (HttpPostedFile)(Anexo.PostedFile); int iFileSize = file.ContentLength; if (iFileSize > 1000000) // 1MB approx (actually less though) { // File is too big so do something here return; } else { if (Anexo.PostedFile.ContentLength < 5242880) { MemoryStream ms = new MemoryStream(Anexo.FileBytes); Attachment anexo = new Attachment(ms, Anexo.PostedFile.FileName); email.anexo = anexo; } else { Label2.Text = "tamanho excedido"; //Response.Redirect("Email.aspx"); //ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Tamanho do arquivo excedido!');"); } } }
- Editado Mariana C. Costa quarta-feira, 19 de julho de 2017 20:25
-
Entendi, veja esse exemplo limitando ate 4MB, seu controle:
<asp:FileUpload ID="Anexo" runat="server" onchange="Javascript: VerificaTamanhoArquivo();" />
O Javascript:
function VerificaTamanhoArquivo() { var fi = document.getElementById('<%= Anexo.ClientID %>'); var maxFileSize = 4194304; // 4MB -> 4 * 1024 * 1024 if (fi.files.length > 0) { for (var i = 0; i <= fi.files.length - 1; i++) { var fsize = fi.files.item(i).size; if (fsize < maxFileSize) { alert("arquivo ok"); } else { alert("arquivo n permitido"); fi.value = null; } } } }
Isso resolve o problema.
- Marcado como Resposta Mariana C. Costa quinta-feira, 20 de julho de 2017 15:04