2009-07-05 20 views
13

Was ist der beste Weg, um die Größe einer Datei während des Uploads mit asp.net und C# zu überprüfen? Ich kann große Dateien hochladen, indem ich meine web.config ohne Probleme ändere. Meine Probleme treten auf, wenn eine Datei hochgeladen wird, die mehr als die zulässige maximale Dateigröße hat.Wie überprüfen Sie die Dateigröße beim Hochladen

Ich habe in die Verwendung von ActiveX-Objekten untersucht, aber das ist nicht Cross-Browser-kompatibel und nicht die beste Antwort auf die Lösung. Ich brauche es, wenn möglich, Cross-Browser-kompatibel zu sein und IE6 zu unterstützen (ich weiß, was du denkst !! Aber 80% meiner Apps-Nutzer sind IE6 und das wird sich in absehbarer Zeit leider nicht ändern).

Hat irgendein Entwickler da draußen das gleiche Problem? Und wenn ja, wie hast du es gelöst?

+0

Vielen Dank für Ihre Kommentare der maxFile Upload-Größe erwähnt wissen. Nachdem ich einige der vorgeschlagenen Lösungen ausprobiert hatte, nutzte ich die Teleriks RAD-Upload-Komponente, mit der ich das tun konnte, was ich brauchte. – Cragly

+0

Dies könnte mit Silverlight oder Flash erfolgen. Für Falsh können Sie [swfupload] (http://www.swfupload.org/) sehen. –

+0

swfupload ist kostenlos und gut. Benutzte es oft und es beantwortet wirklich die Frage. +1 hier. –

Antwort

0

Wir verwenden gerade NeatUpload, um die Dateien hochzuladen.

Während dies die Größe überprüft nach dem Hochladen und damit möglicherweise nicht Ihren Anforderungen entsprechen, und während es die Option hat, SWFUPLOAD zu verwenden, um die Dateien hochzuladen und Größe usw. zu überprüfen, ist es möglich, die Optionen so einzustellen, dass es nicht t verwende diese Komponente.

Aufgrund der Art und Weise, wie sie zu einem Postback-Handler zurückkehren, ist es auch möglich, einen Fortschrittsbalken des Uploads anzuzeigen. Sie können den Upload auch vorzeitig im Handler ablehnen, wenn die Größe der Datei mit der Eigenschaft content size die von Ihnen benötigte Größe überschreitet.

+0

Aha, eine andere Flash-basierte Lösung. –

+0

Eigentlich nein.Abhängig von den Optionen, die Sie wählen, ist kein Blitz involviert, weshalb wir es wählen! –

+0

Es gibt keinen anderen Weg als Flash oder etwas ähnliches, um die Größe der Datei zu überprüfen. Auch habe ich ihre Demoseite inspiziert, sie sind nur Wrapper auf swfupload und ja das ist Flash. –

17

Wenn Sie mit System.Web.UI.WebControls.FileUpload Steuerung:

MyFileUploadControl.PostedFile.ContentLength; 

Gibt die Größe der Datei geschrieben, in Bytes.

+1

Während des Uploads oder nach? –

+1

Während eines Postback ... wird die Datei nur gespeichert, wenn Sie MyFileUploadControl.PostedFile.SaveAs ("file.txt") aufrufen; –

+4

Mit Ausnahme der Postback wird nur ausgelöst, sobald der Upload abgeschlossen ist. Also ist es wirklich * nach * nicht während. – blowdart

7

Dies ist, was ich beim Hochladen einer Datei tun, könnte es Ihnen helfen? Ich überprüfe unter anderem die Dateigröße.

//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

natürlich diese Server-Seite Mark Graham. Die ursprüngliche Frage gefragt "Was ist der beste Weg, um die Größe einer Datei während des Uploads mit asp.net und C# zu überprüfen?" – macou

+0

'var acceptedFileTypes = neuer String [] {" .pdf ",". Doc "...}' 'für (var i = 0; i GooliveR

2

Sie können es auf Safari und FF tun einfach durch

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

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

Was ist mit IE, gibt es eine Alternative das funktioniert auf IE? – GiddyUpHorsey

+0

Sie könnten dies überprüfen http://blog.filepicker.io/post/33906205133/hacking-a-file-api-onto-ie8 –

5

Sie können die Prüfung in asp.net tun, indem Sie diese Schritte ausführen:

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

diese Zeilen in Web hinzufügen .Konfigurationsdatei.
Normale Datei Upload-Größe ist 4 MB. Hier unter system.webmaxRequestLength erwähnt in KB und in system.webServermaxAllowedContentLength wie in 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> 

und wenn Sie möchten in web.config verwenden, um die gegebene Linie in .cs Seite

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

wo kann ich den Fehler generiert, wenn Anfrage tatsächlich über Limit gehen? – Ayyash

Verwandte Themen