在上传之前,我已经获得了这个 JavaScript 脚本来限制最大文件大小,但我不确定如何使用我当前的代码来实现它。
这是JavaScript:
<script type="text/javascript">
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
console.log(f.size); /*<--Here is your size of the file! :D*/
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
还有我的 HTML:
<label>Upload Image</label>
<input type="file" name="image" /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="5120" /></p>
<p><input type="submit" id="submit" value="Upload" />
修改后的代码:
<p><label>Upload Image</label>
<script type="text/javascript">
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
var max_size = 5120; // Max file size
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
// console.log(f.size);
if(f.size > max_size) { // Check if file size is larger than max_size
alert("Sorry, but the file that you selected is too large. Please upload a file that is no larger than " + max_size + " KB.");
return false;
} // end if
} // end for loop
} // end function
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
<input type="file" name="image" id="files"/><br />
<input type="hidden" name="MAX_FILE_SIZE" value="5120" /></p>
<p><input type="submit" id="submit" value="Upload" />
</p>
<p> </p>
</form>