How to retrieve the size of a file before uploading it?

别等时光非礼了梦想. 提交于 2019-12-06 00:33:43

问题


I have an file input tag in my web app. I'd like to check that the file isn't too big before sending it to the server. Of course, I still have validation server side. Is there any way to do this with JavaScript? It must work in IE7+ and FF3+. Thank you.

EDIT: somefileinputobject.files[0].filesize works in FF, but not IE.


回答1:


It's a hard problem. You have to do it with AJAX, and use the filesize headers sent by the browser to the server on the POST request.

Yahoo's UI Library has a tool to help with this. YUI Uploader




回答2:


Javascript cannot do this. It would have serious security issues. Perhaps flash can though.




回答3:


Cannot be reliably done with Javascript for all browsers, but you can limit the total size of the posted data from the web.config




回答4:


Short answer: No, you should handle this on the server.

Long answer: Not reliable. With IE you could do something like:

function checkSize(filespec) {
var fso, f, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.GetFile(filespec);
s = f.size;
// Do something with var s
}

But this can easily be comprimised by the browser's security settings or the usage of another browser or platform.




回答5:


You really don't have a lot of options if you are using the traditional file input control. You cannot check it on the client side and it will hit your configured maxRequestLength before you get the opportunity to check it server side. You can catch the exception that occurs when the maxRequestLength is exceeded though.



来源:https://stackoverflow.com/questions/547292/how-to-retrieve-the-size-of-a-file-before-uploading-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!