Как проверить размер файла при загрузке

Каков наилучший способ проверить размер файла во время загрузки с помощью asp.net и С#? Я могу загружать большие файлы, изменяя свой web.config без проблем. Мои проблемы возникают при загрузке файла, который больше, чем мой максимальный размер файла.

Я изучил использование объектов activex, но это не совместимо с браузером, а не лучшим ответом на решение. Мне нужно, чтобы он был совместим с браузером по возможности и поддерживал IE6 (я знаю, о чем вы думаете! Однако 80% пользователей моих приложений - это IE6, и это вряд ли скоро изменится).

Есть ли у кого-нибудь из разработчиков такая же проблема? И если да, то как вы его решили?

Ответы

Ответ 1

Если вы используете System.Web.UI.WebControls.FileUpload control:

MyFileUploadControl.PostedFile.ContentLength;

Возвращает размер размещенного файла в байтах.

Ответ 2

Это то, что я делаю при загрузке файла, это может вам помочь? Я делаю проверку на размер файла среди прочего.

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

Вы можете выполнить проверку в 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

Добавьте эти строки в файл Web.Config.
Нормальный размер загрузки файлов - 4 МБ. Здесь Under 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>

и если вы хотите знать размер загрузки maxFile, указанный в web.config, используйте данную строку на странице .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

Вы можете сделать это в Safari и FF просто

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

alert(file_field.files[0].fileSize)

Ответ 6

В настоящее время мы используем NeatUpload для загрузки файлов.

В то время как это делает загрузку почты проверки размера и поэтому может не соответствовать вашим требованиям, и, хотя у нее есть возможность использовать SWFUPLOAD для загрузки файлов и проверки размера и т.д., можно установить такие параметры, чтобы они не используйте этот компонент.

В связи с тем, как они отправляются обратно обработчику обратной связи, также можно показать индикатор выполнения загрузки. Вы также можете отказаться от загрузки в начале обработчика, если размер файла с использованием свойства размера содержимого превышает требуемый размер.

Ответ 7

Вот полный пример

 <!DOCTYPE HTML>
    <html>
    <head>
    <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
    <title>Show File Data</title>
    <style type='text/css'>
    body {
        font-family: sans-serif;
    }
    </style>
    <script type='text/javascript'>
    function showFileSize() {
        var input, file;

        // (Can't use `typeof FileReader === "function"` because apparently
        // it comes back as "object" on some browsers. So just see if it there
        // at all.)
        if (!window.FileReader) {
            bodyAppend("p", "The file API isn't supported on this browser yet.");
            return;
        }

        input = document.getElementById('fileinput');
        if (!input) {
            bodyAppend("p", "Um, couldn't find the fileinput element.");
        }
        else if (!input.files) {
            bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
        }
        else if (!input.files[0]) {
            bodyAppend("p", "Please select a file before clicking 'Load'");
        }
        else {
            file = input.files[0];
            bodyAppend("p", "File " + file.name + " is " + file.size + " bytes in size");
        }
    }

    function bodyAppend(tagName, innerHTML) {
        var elm;

        elm = document.createElement(tagName);
        elm.innerHTML = innerHTML;
        document.body.appendChild(elm);
    }
    </script>
    </head>
    <body>
    <form action='#' onsubmit="return false;">
    <input type='file' id='fileinput'>
    <input type='button' id='btnLoad' value='Load' onclick='showFileSize();'>
    </form>
    </body>
    </html>