开发者

Uploading multiple files with size restriction in Javascript

开发者 https://www.devze.com 2022-12-24 06:27 出处:网络
Can anybody tell me how i can upload multiple files with size restriction in javasc开发者_运维技巧ript.You can\'t.

Can anybody tell me how i can upload multiple files with size restriction in javasc开发者_运维技巧ript.


You can't.

You would need to use an alternative, e.g. a Flash-based uploader like SWFUpload.


Multiple files you can do, via multiple <input type="file"> elements. HTML5 (at least) also provides the multiple attribute for a single <input type="file"> element, which is supported by Chrome and Firefox at least (but not IE).

File size restriction you can't do with JavaScript in the browser (yet, except for Firefox 3.6; see below), because you can't access the file system and so have no idea how large the file is prior to the form being submitted. All you can do is (server side) limit the size of allowed requests and (if you set that limit larger than an individual file size you want to allow) throw away any files larger than the limit. (Not ideal.) As Pekka said, you can use alternatives, but of course they may have their own issues (like Flash support on Linux, for instance).

So what do I mean by "yet"? There's a new DOM API from the HTML5 folks: The File API. And it does exactly what it says it does, give JavaScript access to the selected files the user has specifically granted access to via the <input type="file"> element. As yet, I believe only Firefox 3.6+ supports it (it's a Mozilla initiative, adopted by the W3C), but there's talk of Chrome supporting it by Q2 2010 (so, any minute now), and I can't imagine Safari and Opera being far behind (if they're not there already). It'll be interesting to see if Microsoft can jump on the HTML5 bandwagon and start to reclaim their once-forefront position in web technologies. ("Huh? Microsoft leading web technologies?" I hear you ask. Yes -- these are the people who, once upon a time, brought you the fastest, least-buggy browser for Windows there was. These are the people who invented Ajax. It's so easy to forget that. They completely lost their way for several years — and lost all the cred they once had — but there was a time...)


You can always filter out those files with size exceeding based on your need. For example I'm filtering files with less than 5mb here, filterFiles variable only has files less than 5mb:

var filteredFiles = fileList.filter(function(file){
   return file.size <= 5000000; //5mb
});

ES6 method would look like this:

const filteredFiles = fileList.filter((file) => (file.size <= 5000000));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号