2009-07-05 21 views
13

¿Cuál es la mejor manera de verificar el tamaño de un archivo durante la carga usando asp.net y C#? Puedo cargar archivos grandes alterando mi web.config sin ningún problema. Mis problemas surgen cuando se carga un archivo que es más que mi tamaño máximo de archivo permitido.Cómo comprobar el tamaño del archivo al cargar

He examinado el uso de objetos activex pero no es compatible con el navegador cruzado y no es la mejor respuesta a la solución. Necesito que sea compatible con varios navegadores si es posible y que sea compatible con IE6 (¡sé lo que estás pensando! Sin embargo, el 80% de mis usuarios de aplicaciones son IE6 y esto no va a cambiar pronto por desgracia).

¿Alguna de las partes del desarrollo ha tenido el mismo problema? Y si es así, ¿cómo lo resolviste?

+0

Gracias por todos sus comentarios. Después de probar algunas de las soluciones sugeridas, terminé usando el componente de carga RAD de Teleriks que me permitió hacer lo que necesitaba. – Cragly

+0

Esto podría hacerse con Silverlight o Flash. Para Falsh puedes ver [swfupload] (http://www.swfupload.org/). –

+0

swfupload es gratis y bueno. Lo usé muchas veces y realmente responde la pregunta. +1 aquí. –

Respuesta

0

Actualmente estamos utilizando NeatUpload para cargar los archivos.

Si bien esto hace que el tamaño controle la carga de la publicación, puede que no cumpla con sus requisitos y, si bien tiene la opción de usar SWFUPLOAD para cargar archivos y verificar tamaño, es posible configurar las opciones de manera que no usar este componente

Debido a la forma en que publican en un controlador de devolución de datos también es posible mostrar una barra de progreso de la carga. También puede rechazar la carga anticipadamente en el controlador si el tamaño del archivo, utilizando la propiedad de tamaño de contenido, excede el tamaño que necesita.

+0

Aha, otra solución basada en Flash. –

+0

Realmente no.Dependiendo de las opciones que elija, no hay flash involucrado, ¡por eso lo elegimos! –

+0

No hay otra manera que flash o algo similar para verificar el tamaño del archivo. También he inspeccionado su página de demostración, solo están envolviendo swfupload y sí esto es Flash. –

17

Si está utilizando el control System.Web.UI.WebControls.FileUpload:

MyFileUploadControl.PostedFile.ContentLength; 

devuelve el tamaño del archivo enviado, en bytes.

+1

Durante la carga, o después? –

+1

Durante una devolución de datos ... el archivo se guarda solo cuando se llama a MyFileUploadControl.PostedFile.SaveAs ("file.txt"); –

+4

Excepto que la devolución de datos solo se activa una vez que finaliza la carga. Entonces, en realidad es * después * no durante. – blowdart

7

Esto es lo que hago al subir un archivo, ¿podría ser útil? Hago un control sobre el tamaño del archivo, entre otras cosas.

//did the user upload any file? 
      if (FileUpload1.HasFile) 
      { 
       //Get the name of the file 
       string fileName = FileUpload1.FileName; 

      //Does the file already exist? 
      if (File.Exists(Server.MapPath(ConfigurationManager.AppSettings["fileUploadPath"].ToString() + fileName))) 
      { 
       PanelError.Visible = true; 
       lblError.Text = "A file with the name <b>" + fileName + "</b> already exists on the server."; 
       return; 
      } 

      //Is the file too big to upload? 
      int fileSize = FileUpload1.PostedFile.ContentLength; 
      if (fileSize > (maxFileSize * 1024)) 
      { 
       PanelError.Visible = true; 
       lblError.Text = "Filesize of image is too large. Maximum file size permitted is " + maxFileSize + "KB"; 
       return; 
      } 

      //check that the file is of the permitted file type 
      string fileExtension = Path.GetExtension(fileName); 

      fileExtension = fileExtension.ToLower(); 

      string[] acceptedFileTypes = new string[7]; 
      acceptedFileTypes[0] = ".pdf"; 
      acceptedFileTypes[1] = ".doc"; 
      acceptedFileTypes[2] = ".docx"; 
      acceptedFileTypes[3] = ".jpg"; 
      acceptedFileTypes[4] = ".jpeg"; 
      acceptedFileTypes[5] = ".gif"; 
      acceptedFileTypes[6] = ".png"; 

      bool acceptFile = false; 

      //should we accept the file? 
      for (int i = 0; i <= 6; i++) 
      { 
       if (fileExtension == acceptedFileTypes[i]) 
       { 
        //accept the file, yay! 
        acceptFile = true; 
       } 
      } 

      if (!acceptFile) 
      { 
       PanelError.Visible = true; 
       lblError.Text = "The file you are trying to upload is not a permitted file type!"; 
       return; 
      } 

      //upload the file onto the server 
      FileUpload1.SaveAs(Server.MapPath(ConfigurationManager.AppSettings["fileUploadPath"].ToString() + fileName)); 
     }` 
+0

, por supuesto, este lado del servidor Mark Graham. La pregunta original fue "¿Cuál es la mejor manera de verificar el tamaño de un archivo durante la carga usando asp.net y C#?" – macou

+0

'var acceptedFileTypes = new string [] {" .pdf ",". Doc "...}' 'for (var i = 0; i GooliveR

2

Puede hacerlo en Safari y FF simplemente

<input name='file' type='file'>  

alert(file_field.files[0].fileSize) 
+1

¿Qué pasa con IE, hay una alternativa? que funciona en IE? – GiddyUpHorsey

+0

Puede consultar este http://blog.filepicker.io/post/33906205133/hacking-a-file-api-onto-ie8 –

5

Usted puede hacer la comprobación en asp.net haciendo estos pasos:

protected void UploadButton_Click(object sender, EventArgs e) 
{ 
    // Specify the path on the server to 
    // save the uploaded file to. 
    string savePath = @"c:\temp\uploads\"; 

    // Before attempting to save the file, verify 
    // that the FileUpload control contains a file. 
    if (FileUpload1.HasFile) 
    {     
     // Get the size in bytes of the file to upload. 
     int fileSize = FileUpload1.PostedFile.ContentLength; 

     // Allow only files less than 2,100,000 bytes (approximately 2 MB) to be uploaded. 
     if (fileSize < 2100000) 
     { 

      // Append the name of the uploaded file to the path. 
      savePath += Server.HtmlEncode(FileUpload1.FileName); 

      // Call the SaveAs method to save the 
      // uploaded file to the specified path. 
      // This example does not perform all 
      // the necessary error checking.    
      // If a file with the same name 
      // already exists in the specified path, 
      // the uploaded file overwrites it. 
      FileUpload1.SaveAs(savePath); 

      // Notify the user that the file was uploaded successfully. 
      UploadStatusLabel.Text = "Your file was uploaded successfully."; 
     } 
     else 
     { 
      // Notify the user why their file was not uploaded. 
      UploadStatusLabel.Text = "Your file was not uploaded because " + 
            "it exceeds the 2 MB size limit."; 
     } 
    } 
    else 
    { 
     // Notify the user that a file was not uploaded. 
     UploadStatusLabel.Text = "You did not specify a file to upload."; 
    } 
} 
4

Añadir estas líneas en Web .Archivo de configuración.
El tamaño normal de carga de archivos es de 4MB. Aquí bajo system.webmaxRequestLength mencionado en KB y en system.webServermaxAllowedContentLength como en Bytes.

<system.web> 
     . 
     . 
     . 
     <httpRuntime executionTimeout="3600" maxRequestLength="102400" useFullyQualifiedRedirectUrl="false" delayNotificationTimeout="60"/> 
    </system.web> 


    <system.webServer> 
     . 
     . 
     . 
     <security> 
      <requestFiltering> 
      <requestLimits maxAllowedContentLength="1024000000" /> 
      <fileExtensions allowUnlisted="true"></fileExtensions> 
      </requestFiltering> 
     </security> 
    </system.webServer> 

y si quieres saber el tamaño maxFile carga mencionada en web.config utilizar la línea dada en la página .cs

System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); 
    HttpRuntimeSection section = config.GetSection("system.web/httpRuntime") as HttpRuntimeSection; 

    //get Max upload size in MB     
    double maxFileSize = Math.Round(section.MaxRequestLength/1024.0, 1); 

    //get File size in MB 
    double fileSize = (FU_ReplyMail.PostedFile.ContentLength/1024)/1024.0; 

    if (fileSize > 25.0) 
    { 
      ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Alert", "alert('File Size Exceeded than 25 MB.');", true); 
      return; 
    } 
+1

¿dónde puedo ver el error generado si la solicitud va más allá del límite? – Ayyash

Cuestiones relacionadas