【问题标题】:How to check file size on upload如何在上传时检查文件大小
【发布时间】:2009-07-05 20:14:42
【问题描述】:

使用 asp.net 和 C# 在上传期间检查文件大小的最佳方法是什么?我可以通过更改我的 web.config 来上传大文件而不会出现任何问题。当上传的文件超过我允许的最大文件大小时,我的问题就会出现。

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

有没有任何开发者遇到过同样的问题?如果是这样,您是如何解决的?

【问题讨论】:

  • 这可以通过 Silverlight 或 Flash 完成。对于 Falsh,您可以查看 swfupload
  • swfupload 是免费的,而且很好。多次使用它,它确实回答了这个问题。在这里 +1。
  • 迈克,你为什么回滚我所做的修订?
  • Dreas,你为什么要修改这个版本?你添加信息了吗?
  • 感谢您的所有 cmets。在尝试了一些建议的解决方案后,我最终使用了 Teleriks RAD 上传组件,它允许我做我需要做的事情。

标签: c# asp.net


【解决方案1】:

您可以通过执行以下步骤在 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.";
    }
}

【讨论】:

    【解决方案2】:

    如果你使用System.Web.UI.WebControls.FileUpload控制:

    MyFileUploadControl.PostedFile.ContentLength;
    

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

    【讨论】:

    • 回发期间...仅当您调用 MyFileUploadControl.PostedFile.SaveAs("file.txt"); 时才会保存文件;
    • 只有在上传完成后才会触发回发。所以它实际上是之后而不是期间。
    • 由于安全措施,客户端技术 (javascript) 无法访问本地文件,因此您无法在文件发布到服务器之前检查文件的大小。
    • 您现在可以这样做,而无需访问本地文件。见This Answer
    【解决方案3】:

    在 Web.Config 文件中添加这些行。
    正常文件上传大小为 4MB。这里在 system.web maxRequestLength 下在 KB 和 system.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>
    

    如果您想知道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;
         }
    

    【讨论】:

    • 如果请求确实超出限制,我在哪里可以捕获生成的错误?
    【解决方案4】:

    这是我在上传文件时所做的,它可能对你有帮助吗?我会检查文件大小等。

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

    【讨论】:

    • 当然是服务器端 Mark Graham。最初的问题是“使用 asp.net 和 C# 在上传期间检查文件大小的最佳方法是什么?”
    • var acceptedFileTypes = new string[] { ".pdf",".doc" ... } for(var i = 0; i &lt; acceptedFileTypes .Length; i++)
    【解决方案5】:

    你可以在 Safari 和 FF 上简单地通过

    <input name='file' type='file'>    
    
    alert(file_field.files[0].fileSize)
    
    【解决方案6】:

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

    虽然这会在上传后检查大小,因此可能无法满足您的要求,虽然它可以选择使用 SWFUPLOAD 上传文件和检查大小等,但可以设置选项使其不使用这个组件。

    由于他们回发到回发处理程序的方式,还可以显示上传的进度条。如果使用 content size 属性的文件大小超过了您需要的大小,您也可以在处理程序中提前拒绝上传。

    【讨论】:

    • 啊哈,另一个基于 Flash 的解决方案。
    • 其实没有。根据您选择的选项,不涉及闪光灯,这就是我们选择它的原因!
    • 除了闪存或类似的东西来检查文件的大小之外,没有其他方法。我还检查了他们的演示页面,它们只是 swfupload 的包装器,是的,这是 Flash。
    猜你喜欢
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    • 2013-04-30
    • 2017-01-30
    • 1970-01-01
    相关资源
    最近更新 更多