2009-07-05 15 views
13

asp.net 및 C#을 사용하여 업로드하는 동안 파일 크기를 확인하는 가장 좋은 방법은 무엇입니까? 어떤 문제없이 web.config를 변경하여 대용량 파일을 업로드 할 수 있습니다. 허용 된 최대 파일 크기를 초과하여 파일을 업로드하면 문제가 발생합니다.업로드시 파일 크기 확인 방법

나는 activex 객체를 사용하는 방법을 살펴 보았지만 크로스 브라우저와 호환되지 않으며 솔루션에 대한 최선의 해결책이 아닙니다. 가능하다면 크로스 브라우저 호환이되어야하고 IE6를 지원해야합니다. (내 앱 사용자의 80 %는 IE6이며, 불행히도 언제든지 변경되지 않을 것입니다.)

동일한 문제가 발생하는 개발자가 있습니까? 그리고 만약 그렇다면 어떻게 해결 했습니까?

+0

감사 주어진 줄을 사용 알고 싶다면. 제안 된 솔루션 중 일부를 시도한 후에 Teleriks RAD 업로드 구성 요소를 사용하여 결국 내가 필요한 것을 수행 할 수있었습니다. – Cragly

+0

이것은 Silverlight 또는 Flash로 수행 할 수 있습니다. Falsh에게는 [swfupload] (http://www.swfupload.org/)가 있습니다. –

+0

swfupload는 무료이며 좋습니다. 여러 번 사용했고 실제로 질문에 답합니다. 여기 +1. –

답변

0

현재 NeatUpload를 사용하여 파일을 업로드하고 있습니다.

크기 확인 게시 후 업로드가 사용자의 요구 사항을 충족하지 못할 수 있지만 SWFUPLOAD를 사용하여 파일을 업로드하고 크기를 확인하는 등의 옵션을 사용할 수는 있지만 옵션을 설정하여 ' 이 구성 요소를 사용하십시오.

포스트 백 처리기로 다시 게시하는 방식으로 인해 업로드 진행률 표시 줄을 표시 할 수도 있습니다. 콘텐츠 크기 속성을 사용하는 파일 크기가 필요한 크기를 초과하는 경우 처리기에서 일찍 업로드를 거부 할 수도 있습니다.

MyFileUploadControl.PostedFile.ContentLength; 

바이트에 게시 된 파일의 크기를 반환

+0

다른 플래시 기반 솔루션 인 Aha. –

+0

사실 아니요.선택하는 옵션에 따라 관련 플래시가 없기 때문에 선택할 수 있습니다! –

+0

다른 방법은 플래시 또는 뭔가 simmilar 파일의 크기를 확인하는 것입니다. 또한 나는 그들의 데모 페이지를 살펴 보았습니다. swfupload에 대한 래퍼이며 예, Flash입니다. –

17

당신은 System.Web.UI.WebControls.FileUpload 제어를 사용하는 경우.

+1

업로드하는 동안 또는 이후에? –

+1

포스트 백 중 ... 파일은 MyFileUploadControl.PostedFile.SaveAs ("file.txt")를 호출 할 때만 저장됩니다. –

+4

포스트 백은 업로드가 완료된 후에 만 ​​트리거됩니다. 그래서 실제로 * 후에 * 않습니다. – blowdart

7

파일을 업로드 할 때 내가하는 일은 도움이 될만한가요? 나는 다른 것들 사이에서 파일 크기를 확인합니다.

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

물론이 서버 측 Mark Graham을 참조하십시오. 원래 질문 "asp.net 및 C#을 사용하여 업로드하는 동안 파일의 크기를 확인하는 가장 좋은 방법은 무엇입니까?" – macou

+0

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

2

다음 단계를 수행하여 당신은 asp.net에서 검사를 할 수있는 간단

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

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

IE는 어떨까요? 그건 IE에서 작동합니까? – GiddyUpHorsey

+0

이것을 확인하실 수 있습니다 http://blog.filepicker.io/post/33906205133/hacking-a-file-api-onto-ie8 –

5

에 의해 사파리와 FF에 작업을 수행 할 수 있습니다

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

웹에서이 라인을 추가 .Config 파일.
일반적인 파일 업로드 크기는 4MB입니다. 여기에 KB로 언급 된 system.webmaxRequestLengthsystem.webServermaxAllowedContentLength에서와 같이 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> 

당신은 web.config에 언급 된 maxFile 업로드 크기는 모든 의견을 .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

요청이 실제로 한계를 초과하면 생성 된 오류는 어디에서 잡을 수 있습니까? – Ayyash

관련 문제