如何检查文件大小的上传?

时间:2022-12-09 09:42:15

Whats the best way to check the size of a file during upload using asp.net and C#? I can upload large files by altering my web.config without any problems. My issues arises when a file is uploaded which is more than my allowed max file size.

在使用asp.net和c#进行上传时检查文件大小的最佳方法是什么?我可以通过改变我的网络上传大文件。配置没有问题。当上传的文件超过允许的最大文件大小时,就会出现问题。

I have looked into using activex objects but that is not cross browser compatible and not the best answer to the solution. I need it to be cross browser compatible if possible and to support IE6 (i know what you are thinking!! However 80% of my apps users are IE6 and this is not going to change anytime soon unfortunately).

我已经研究过使用activex对象,但这不是跨浏览器兼容的,也不是解决方案的最佳答案。如果可能的话,我需要跨浏览器兼容并支持IE6(我知道你在想什么!)然而,我的应用程序用户中有80%是IE6,不幸的是,这种情况不会很快改变。

Has any dev out there come across the same problem? And if so how did you solve it?

有没有开发人员遇到过同样的问题?如果是的话,你是怎么解决的?

6 个解决方案

#1


17  

If you are using System.Web.UI.WebControls.FileUpload control:

如果你正在使用System.Web.UI.WebControls。FileUpload控件:

MyFileUploadControl.PostedFile.ContentLength;

Returns the size of the posted file, in bytes.

返回已发布文件的大小(以字节为单位)。

#2


8  

This is what I do when uploading a file, it might help you? I do a check on filesize among other things.

这就是我上传文件时所做的事情,可能会对你有所帮助?我对filesize进行了检查。

//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));
        }`

#3


5  

You can do the checking in asp.net by doing these steps:

你可以通过以下步骤在asp.net中进行检查:

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


4  

Add these Lines in Web.Config file.
Normal file upload size is 4MB. Here Under system.web maxRequestLength mentioned in KB and in system.webServer maxAllowedContentLength as in Bytes.

在Web中添加这些行。配置文件。普通文件上传大小为4MB。这里下系统。在KB和system中提到的web maxRequestLength。webServer maxAllowedContentLength以字节为单位。

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

and if you want to know the maxFile upload size mentioned in web.config use the given line in .cs page

如果您想知道web中提到的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;
     }

#5


2  

You can do it on Safari and FF simply by

你可以在Safari和FF上做

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

alert(file_field.files[0].fileSize)

#6


0  

We are currently using NeatUpload to upload the files.

我们目前正在使用tidy upload上传文件。

While this does the size check post upload and so may not meet your requirements, and while it has the option to use SWFUPLOAD to upload the files and check size etc, it is possible to set the options such that it doesn't use this component.

虽然这样做的大小检查后上载,因此可能不满足您的要求,并且它有使用SWFUPLOAD来上载文件和检查大小等选项,但是可以设置选项,使其不使用此组件。

Due to the way they post back to a postback handler it is also possible to show a progress bar of the upload. You can also reject the upload early in the handler if the size of the file, using the content size property, exceeds the size you require.

由于它们返回回发处理程序的方式,也可以显示上传的进度条。如果使用content size属性的文件大小超过了所需的大小,也可以在处理程序的早期拒绝上传。

#1


17  

If you are using System.Web.UI.WebControls.FileUpload control:

如果你正在使用System.Web.UI.WebControls。FileUpload控件:

MyFileUploadControl.PostedFile.ContentLength;

Returns the size of the posted file, in bytes.

返回已发布文件的大小(以字节为单位)。

#2


8  

This is what I do when uploading a file, it might help you? I do a check on filesize among other things.

这就是我上传文件时所做的事情,可能会对你有所帮助?我对filesize进行了检查。

//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));
        }`

#3


5  

You can do the checking in asp.net by doing these steps:

你可以通过以下步骤在asp.net中进行检查:

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


4  

Add these Lines in Web.Config file.
Normal file upload size is 4MB. Here Under system.web maxRequestLength mentioned in KB and in system.webServer maxAllowedContentLength as in Bytes.

在Web中添加这些行。配置文件。普通文件上传大小为4MB。这里下系统。在KB和system中提到的web maxRequestLength。webServer maxAllowedContentLength以字节为单位。

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

and if you want to know the maxFile upload size mentioned in web.config use the given line in .cs page

如果您想知道web中提到的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;
     }

#5


2  

You can do it on Safari and FF simply by

你可以在Safari和FF上做

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

alert(file_field.files[0].fileSize)

#6


0  

We are currently using NeatUpload to upload the files.

我们目前正在使用tidy upload上传文件。

While this does the size check post upload and so may not meet your requirements, and while it has the option to use SWFUPLOAD to upload the files and check size etc, it is possible to set the options such that it doesn't use this component.

虽然这样做的大小检查后上载,因此可能不满足您的要求,并且它有使用SWFUPLOAD来上载文件和检查大小等选项,但是可以设置选项,使其不使用此组件。

Due to the way they post back to a postback handler it is also possible to show a progress bar of the upload. You can also reject the upload early in the handler if the size of the file, using the content size property, exceeds the size you require.

由于它们返回回发处理程序的方式,也可以显示上传的进度条。如果使用content size属性的文件大小超过了所需的大小,也可以在处理程序的早期拒绝上传。