上传文件前请检查文件大小

Check filesize before uploading to file system

本文关键字:检查 文件大小 文件      更新时间:2023-09-26

问个小问题,

我已经对此做了很多研究,但我有不同的方法。

我的问题:我有一个文件上传,在所有的浏览器使用asp.net与VB工作。问题是我们的系统只允许上传不大于1mb的文件。现在,使用后端检查,它将告诉用户文件是否太大,并且他们必须上传一个较小的文件。然而,奇怪的问题是,它将捕获2-3mb超过限制的文件。例如,如果文件是20mb,则不会。如果上传它,我将得到一个讨厌的调试错误,说已请求最大文件大小。

我想做的是在前端进行快速检查,以防止它被发送到后端。

我使用

:

$(function(){
    $('#File1').bind('change', function() {
          alert(this.files[0].size);
        });
});

检查文件大小。它适用于chrome和firefox。但IE除外。我听说如果用户允许在隐私设置中使用ActiveX可以工作。

我可以使用浏览器检测说"嘿,如果IE做activeX其他做jQuery",但我想知道是否有一个比activeX更可靠的方法?

你的问题是由于10之前的所有IE版本都不支持HTML5文件API。因此,考虑到this是您的HTMLInputElement,以下内容将不起作用:

this.files[0].size;

原因是HTMLInputElement.FileList不存在,因为缺乏文件API支持,但您可以通过HTMLInputElement.value获得文件名。但这不是你想要的。你想要得到文件的大小。再一次,由于缺乏文件API支持,IE <10没有提供文件大小信息。因此,检查这些小版本的文件大小的唯一方法是使用ActiveX,即使没有人喜欢这样做。

第一个解决方案(客户端- jQuery)

你提出

:

我可以使用浏览器检测说"嘿,如果IE执行activeX,则执行jQuery"

如果你想这样做,你可以这样写:

$(function(){
    $('#File1').bind('change', function() {
        var maxFileSize = 1024000; // 1MB -> 1000 * 1024
        var fileSize;
        // If current browser is IE < 10, use ActiveX
        if (isIE() && isIE() < 10) {
            var filePath = this.value;
            if (filePath != '') {
                var AxFSObj = new ActiveXObject("Scripting.FileSystemObject");
                var AxFSObjFile = AxFSObj.getFile(filePath);
                fileSize = AxFSObjFile.size;
            }
        } else {
            // IE >= 10 or not IE
            if (this.value != '') {
                fileSize = this.files[0].size;
            }
        }
        if (fileSize < maxFileSize) {
            // Enable submit button and remove any error message
            $('#button_fileUpload').prop('disabled', false);
            $('#lbl_uploadMessage').text('');
        } else {
            // Disable submit button and show error message
            $('#button_fileUpload').prop('disabled', true);
            $('#lbl_uploadMessage').text('File too big !');
        }
    });
});
// Check if the browser is Internet Explorer
function isIE() {
    var myNav = navigator.userAgent.toLowerCase();
    return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
} 

警告!

在盲目复制这段代码之前,请注意ActiveX解决方案实际上是一个很差的解决方案。要使其工作,用户必须更改其Internet选项。此外,这种解决方案不适用于公共站点,只适用于内部网应用程序。

但是我想知道是否有比ActiveX更可靠的方法?

不,没有IE <10

第二个解决方案(jQuery插件)

你可以使用jQuery文件上传。你可以很容易地得到它的大小。

第三种方案(服务器端- VB.NET)

考虑到你有这些asp控件:

<asp:FileUpload ID="fileUpload" runat="server" />
<asp:Button ID="button_fileUpload" runat="server" Text="Upload File" />
<asp:Label ID="lbl_uploadMessage" runat="server" Text="" ForeColor="Red" />

一旦与服务器端交互,您可以检查所选择的文件大小。例如,我在这里检查文件的大小,一旦用户点击上传按钮。

Protected Sub btnFileUpload_click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button_fileUpload.Click
    ' A temporary folder
    Dim savePath As String = "c:'temp'uploads'"
    If (fileUpload.HasFile) Then
        Dim fileSize As Integer = fileUpload.PostedFile.ContentLength
        ' 1MB -> 1000 * 1024
        If (fileSize < 1024000) Then
            savePath += Server.HtmlEncode(fileUpload.FileName)
            fileUpload.SaveAs(savePath)
            lbl_uploadMessage.Text = "Your file was uploaded successfully."
        Else
            lbl_uploadMessage.Text = "Your file was not uploaded because " +
                                     "it exceeds the 1 MB size limit."
        End If
    Else
        lbl_uploadMessage.Text = "You did not specify a file to upload."
    End If
End Sub

编辑

正如你所说的,最后一个解决方案不适用于太大的文件。要使此解决方案工作,您必须在web.config文件中增加最大上载文件大小:

<configuration>
    <system.web>
        <httpRuntime maxRequestLength="52428800" /> <!--50MB-->
    </system.web>
</configuration>