问题描述
我只想限制用户可以上传的文件的大小.
I would like to simply limit the size of a file that a user can upload.
我认为maxlength = 20000 = 20k,但这似乎根本不起作用.
I thought maxlength = 20000 = 20k but that doesn't seem to work at all.
我在Rails上运行,而不是在PHP上运行,但是我认为在HTML/CSS的客户端进行此操作要简单得多,或者作为最后一种使用jQuery的方法.这是如此基本,尽管必须缺少一些我不知道或不知道的HTML标记.
I am running on Rails, not PHP, but was thinking it'd be much simpler to do it client side in the HTML/CSS, or as a last resort using jQuery. This is so basic though that there must be some HTML tag I am missing or not aware of.
希望支持IE7 +,Chrome,FF3.6 +.我想我可以在需要时仅支持IE8 +.
Looking to support IE7+, Chrome, FF3.6+. I suppose I could get away with just supporting IE8+ if necessary.
谢谢.
推荐答案
这是完全可能的.使用Javascript.
This is completely possible. Use Javascript.
我使用jQuery选择输入元素.我设置了一个on change事件.
I use jQuery to select the input element. I have it set up with an on change event.
$("#aFile_upload").on("change", function (e) {
var count=1;
var files = e.currentTarget.files; // puts all files into an array
// call them as such; files[0].size will get you the file size of the 0th file
for (var x in files) {
var filesize = ((files[x].size/1024)/1024).toFixed(4); // MB
if (files[x].name != "item" && typeof files[x].name != "undefined" && filesize <= 10) {
if (count > 1) {
approvedHTML += ", "+files[x].name;
}
else {
approvedHTML += files[x].name;
}
count++;
}
}
$("#approvedFiles").val(approvedHTML);
});
上面的代码在提交实际发生之前,将我认为值得保留的所有文件名保存到提交页面.我使用jQuery将批准的"文件添加到输入元素的val中,以便表单提交将发送我要保存的文件的名称.所有文件都将被提交,但是,现在在服务器端,我们必须将它们过滤掉.我还没有为此编写任何代码,但是请发挥您的想象力.我假设可以通过for循环并匹配从输入字段发送来的名称并将它们与$ _FILES(PHP Superglobal,抱歉,我不知道ruby file variable)变量相匹配来完成此操作.
The code above saves all the file names that I deem worthy of persisting to the submission page, before the submit actually happens. I add the "approved" files to an input element's val using jQuery so a form submit will send the names of the files I want to save. All the files will be submitted, however, now on the server side we do have to filter these out. I haven't written any code for that yet, but use your imagination. I assume one can accomplish this by a for loop and matching the names sent over from the input field and match them to the $_FILES(PHP Superglobal, sorry I dont know ruby file variable) variable.
我的意思是,您可以在提交文件之前检查文件.我这样做,然后在用户提交表单之前将其输出给用户,以使他们知道他们要上传到我的站点的内容.任何不符合条件的内容都不会显示给用户,因此他们应该知道,不会保存太大的文件.这应该适用于所有浏览器,因为我没有使用FormData对象.
My point is you can do checks for files before submission. I do this and then output it to the user before he/she submits the form, to let them know what they are uploading to my site. Anything that doesn't meet the criteria does not get displayed back to the user and therefore they should know, that the files that are too large wont be saved. This should work on all browsers because I'm not using FormData object.
这篇关于限制文件上传的大小(html输入元素)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!