Javascript 上传前获取文件大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7497404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:30:39  来源:igfitidea点击:

Get file size before uploading

javascriptjqueryajaxfile-uploadfilesize

提问by Nisanth Kumar

Is there any way to find out the file size before uploading the file using AJAX / PHP in change event of input file?

在输入文件的更改事件中使用 AJAX/PHP 上传文件之前,有没有办法找出文件大小?

回答by Brij

For the HTML bellow

对于下面的 HTML

<input type="file" id="myFile" />

try the following:

尝试以下操作:

//binds to onchange event of your input field
$('#myFile').bind('change', function() {

  //this.files[0].size gets the size of your file.
  alert(this.files[0].size);

});

See following thread:

请参阅以下线程:

How to check file input size with jQuery?

如何使用jQuery检查文件输入大小?

回答by Behnam Bakhshi

<script type="text/javascript">
function AlertFilesize(){
    if(window.ActiveXObject){
        var fso = new ActiveXObject("Scripting.FileSystemObject");
        var filepath = document.getElementById('fileInput').value;
        var thefile = fso.getFile(filepath);
        var sizeinbytes = thefile.size;
    }else{
        var sizeinbytes = document.getElementById('fileInput').files[0].size;
    }

    var fSExt = new Array('Bytes', 'KB', 'MB', 'GB');
    fSize = sizeinbytes; i=0;while(fSize>900){fSize/=1024;i++;}

    alert((Math.round(fSize*100)/100)+' '+fSExt[i]);
}
</script>

<input id="fileInput" type="file" onchange="AlertFilesize();" />

Work on IE and FF

在 IE 和 FF 上工作

回答by jaggedsoft

Here's a simple example of getting the size of a file before uploading. It's using jQuery to detect whenever the contents are added or changed, but you can still get files[0].sizewithout using jQuery.

这是一个在上传之前获取文件大小的简单示例。它使用 jQuery 来检测何时添加或更改内容,但您仍然可以files[0].size不使用 jQuery。

$(document).ready(function() {
  $('#openFile').on('change', function(evt) {
    console.log(this.files[0].size);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="upload.php" enctype="multipart/form-data" method="POST" id="uploadform">
  <input id="openFile" name="img" type="file" />
</form>

Here's a more complete example, some proof of concept code to Drag and Drop files into FormDataand upload via POST to a server. It includes a simple check for file size.

这是一个更完整的示例,一些用于将文件拖放到 FormData并通过 POST 上传到服务器的概念验证代码。它包括对文件大小的简单检查。

回答by Hoang Le

I had the same problem and seems like we haven't had an accurate solution. Hope this can help other people.

我遇到了同样的问题,似乎我们还没有准确的解决方案。希望这可以帮助其他人。

After take time exploring around, I finally found the answer. This is my code to get file attach with jQuery:

经过一段时间的探索,我终于找到了答案。这是我使用 jQuery 获取文件附加的代码:

var attach_id = "id_of_attachment_file";
var size = $('#'+attach_id)[0].files[0].size;
alert(size);

This is just the example code for getting the file size. If you want do other stuffs, feel free to change the code to satisfy your needs.

这只是获取文件大小的示例代码。如果您想做其他事情,请随时更改代码以满足您的需求。

回答by ucefkh

Best solution working on all browsers ;)

适用于所有浏览器的最佳解决方案;)

function GetFileSize(fileid) {
    try {
        var fileSize = 0;
        // for IE
        if(checkIE()) { //we could use this $.browser.msie but since it's deprecated, we'll use this function
            // before making an object of ActiveXObject, 
            // please make sure ActiveX is enabled in your IE browser
            var objFSO = new ActiveXObject("Scripting.FileSystemObject");
            var filePath = $("#" + fileid)[0].value;
            var objFile = objFSO.getFile(filePath);
            var fileSize = objFile.size; //size in b
            fileSize = fileSize / 1048576; //size in mb 
        }
        // for FF, Safari, Opeara and Others
        else {
            fileSize = $("#" + fileid)[0].files[0].size //size in b
            fileSize = fileSize / 1048576; //size in mb 
        }
        alert("Uploaded File Size is" + fileSize + "MB");
    }
    catch (e) {
        alert("Error is :" + e);
    }
}

from http://www.dotnet-tricks.com/Tutorial/jquery/HHLN180712-Get-file-size-before-upload-using-jquery.html

来自http://www.dotnet-tricks.com/Tutorial/jquery/HHLN180712-Get-file-size-before-upload-using-jquery.html

UPDATE :We'll use this function to check if it's IE browser or not

更新:我们将使用此功能来检查它是否是 IE 浏览器

function checkIE() {
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)){  
        // If Internet Explorer, return version number
        alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
    } else {
        // If another browser, return 0
        alert('otherbrowser');
    }

    return false;
}

回答by vishay hard

$(document).ready(function() {
  $('#openFile').on('change', function(evt) {
    console.log(this.files[0].size);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="upload.php" enctype="multipart/form-data" method="POST" id="uploadform">
  <input id="openFile" name="img" type="file" />
</form>

回答by Sandeep G

Browsers with HTML5 support has files property for input type. This will of course not work in older IE versions.

支持 HTML5 的浏览器具有用于输入类型的 files 属性。这当然不适用于较旧的 IE 版本。

var inpFiles = document.getElementById('#fileID');
for (var i = 0; i < inpFiles.files.length; ++i) {
    var size = inpFiles.files.item(i).size;
    alert("File Size : " + size);
}

回答by Mike

ucefkh's solution worked best, but because $.browser was deprecated in jQuery 1.91, had to change to use navigator.userAgent:

ucefkh 的解决方案效果最好,但因为 $.browser 在 jQuery 1.91 中被弃用,不得不更改为使用 navigator.userAgent:

function IsFileSizeOk(fileid) {
    try {
        var fileSize = 0;
        //for IE
        if (navigator.userAgent.match(/msie/i)) {
            //before making an object of ActiveXObject, 
            //please make sure ActiveX is enabled in your IE browser
            var objFSO = new ActiveXObject("Scripting.FileSystemObject");
            var filePath = $("#" + fileid)[0].value;
            var objFile = objFSO.getFile(filePath);
            var fileSize = objFile.size; //size in b
            fileSize = fileSize / 1048576; //size in mb 
        }
        //for FF, Safari, Opeara and Others
        else {
            fileSize = $("#" + fileid)[0].files[0].size //size in b
            fileSize = fileSize / 1048576; //size in mb 
        }
        return (fileSize < 2.0);
    }
    catch (e) {
        alert("Error is :" + e);
    }
}

回答by kasper Taeymans

you need to do an ajax HEAD request to get the filesize. with jquery it's something like this

您需要执行 ajax HEAD 请求来获取文件大小。使用 jquery 是这样的

  var req = $.ajax({
    type: "HEAD",
    url: yoururl,
    success: function () {
      alert("Size is " + request.getResponseHeader("Content-Length"));
    }
  });

回答by Nicolas Bouvrette

Please do not use ActiveXas chances are that it will display a scary warning message in Internet Explorer and scare your users away.

请不要使用ActiveX,因为它可能会在 Internet Explorer 中显示可怕的警告消息并将您的用户吓跑。

ActiveX warning

ActiveX 警告

If anyone wants to implement this check, they should only rely on the FileListobject available in modern browsers and rely on server side checks only for older browsers (progressive enhancement).

如果有人想实现这个检查,他们应该只依赖于现代浏览器中可用的FileList对象,并且只依赖于旧浏览器的服务器端检查(渐进增强)。

function getFileSize(fileInputElement){
    if (!fileInputElement.value ||
        typeof fileInputElement.files === 'undefined' ||
        typeof fileInputElement.files[0] === 'undefined' ||
        typeof fileInputElement.files[0].size !== 'number'
    ) {
        // File size is undefined.
        return undefined;
    }

    return fileInputElement.files[0].size;
}