2009-07-05 50 views
13

Làm cách nào tốt nhất để kiểm tra kích thước tệp trong khi tải lên bằng asp.net và C#? Tôi có thể tải lên các tệp lớn bằng cách thay đổi web.config của mình mà không gặp bất kỳ sự cố nào. Vấn đề của tôi phát sinh khi tệp được tải lên nhiều hơn kích thước tệp tối đa được phép của tôi.Cách kiểm tra kích thước tệp khi tải lên

Tôi đã xem xét sử dụng các đối tượng activex nhưng không tương thích với trình duyệt chéo và không phải là câu trả lời hay nhất cho giải pháp. Tôi cần nó tương thích với trình duyệt chéo nếu có thể và hỗ trợ IE6 (tôi biết bạn đang nghĩ gì! Tuy nhiên 80% người dùng ứng dụng của tôi là IE6 và điều này sẽ không thay đổi bất cứ lúc nào sớm).

Có bất kỳ nhà phát triển nào có vấn đề tương tự không? Và nếu như vậy làm thế nào bạn giải quyết nó?

+0

Cảm ơn tất cả bình luận của bạn. Sau khi thử một số giải pháp được đề xuất, tôi đã sử dụng thành phần Teleriks RAD upload cho phép tôi làm những gì tôi cần. – Cragly

+0

Điều này có thể được thực hiện với Silverlight hoặc Flash. Đối với Falsh bạn có thể thấy [swfupload] (http://www.swfupload.org/). –

+0

swfupload là miễn phí và tốt. Sử dụng nó nhiều lần và nó thực sự trả lời câu hỏi. +1 ở đây. –

Trả lời

0

Chúng tôi hiện đang sử dụng NeatUpload để tải tệp lên.

Trong khi điều này làm kích thước bài đăng tải lên và vì vậy có thể không đáp ứng yêu cầu của bạn, và trong khi nó có tùy chọn để sử dụng SWFUPLOAD để tải lên các tệp và kiểm tra kích thước vv, có thể thiết lập các tùy chọn như vậy nó không ' t sử dụng thành phần này.

Do cách họ đăng lại trình xử lý đăng lại, bạn cũng có thể hiển thị thanh tiến trình tải lên. Bạn cũng có thể từ chối tải lên sớm trong trình xử lý nếu kích thước của tệp, sử dụng thuộc tính kích thước nội dung, vượt quá kích thước bạn yêu cầu.

+0

Aha, một giải pháp dựa trên Flash khác. –

+0

Thực tế là không.Tùy thuộc vào các tùy chọn bạn chọn, không có flash liên quan, đó là lý do tại sao chúng tôi chọn nó! –

+0

Không có cách nào khác sau đó flash hoặc một cái gì đó simmilar để kiểm tra kích thước của tập tin. Ngoài ra tôi đã kiểm tra trang demo của họ, họ chỉ là wrapper trên swfupload và có đây là Flash. –

17

Nếu bạn đang sử dụng System.Web.UI.WebControls.FileUpload kiểm soát:

MyFileUploadControl.PostedFile.ContentLength; 

Trả về kích thước của tập tin được đăng, tính bằng byte.

+1

Trong khi tải lên, hoặc sau? –

+1

Trong khi đăng lại ... tệp chỉ được lưu khi bạn gọi MyFileUploadControl.PostedFile.SaveAs ("file.txt"); –

+4

Trừ khi đăng lại chỉ được kích hoạt sau khi quá trình tải lên kết thúc. Vì vậy, nó thực sự * sau * không trong suốt. – blowdart

7

Đây là những gì tôi làm khi tải tệp lên, nó có thể giúp bạn? Tôi làm một kiểm tra trên filesize trong số những thứ khác.

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

tất nhiên phía máy chủ Mark Graham này. Câu hỏi ban đầu hỏi "Whats cách tốt nhất để kiểm tra kích thước của một tập tin trong khi tải lên bằng cách sử dụng asp.net và C#?" – macou

+0

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

2

Bạn có thể làm điều đó trên Safari và FF đơn giản bằng cách

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

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

Điều gì về IE, là có một sự thay thế hoạt động trên IE? – GiddyUpHorsey

+0

Bạn có thể kiểm tra http://blog.filepicker.io/post/33906205133/hacking-a-file-api-onto-ie8 –

5

Bạn có thể làm việc kiểm tra trong asp.net bằng cách thực hiện các bước sau:

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

Thêm những dòng trong Web .Tập tin cấu hình.
Kích thước tải lên tệp bình thường là 4MB. Dưới đây theo system.webmaxRequestLength được đề cập trong KB và trong system.webServermaxAllowedContentLength như trong byte.

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

và nếu bạn muốn biết kích thước maxFile upload nêu tại web.config sử dụng dòng được đưa ra trong .cs trang

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

nơi tôi có thể bắt lỗi được tạo nếu yêu cầu thực sự vượt quá giới hạn? – Ayyash

Các vấn đề liên quan