Reputation: 5892
I came across this question while studying for the Microsoft Web-Application Developer exam,
You are implementing a Web page that allows users to upload files to a Web server. The page includes a form that has a Submit button. You want to restrict uploads so that only files smaller than 1 MB can be uploaded.
The answer given was:
Add an ASP.NET FileUpload control and configure it to run on the server. Add a server-side OnClick handler to the form's Submit button to save the file only if the file size is allowed
But wouldn't this mean that the file would have already been uploaded to the server? and we are just choosing whether to save it or not? Can it be done on the client Side?
Upvotes: 3
Views: 1634
Reputation: 1042
using IE :
<html>
<head>
<script>
function getSize()
{
var myFSO = new ActiveXObject("Scripting.FileSystemObject");
var filepath = document.upload.file.value;
var thefile = myFSO.getFile(filepath);
var size = thefile.size;
alert(size + " bytes");
}
</script>
</head>
<body>
<form name="upload">
<input type="file" name="file">
<input type="button" value="Size?" onClick="getSize();">
</form>
</body>
</html>
using Chrome or Firefox : With jQuery and the HTML5 File API specification implemented, you can use this simple snippet to access file properties such as size:
//binds to onchange event of your input field
$('#myFile').bind('change', function() {
alert(this.files[0].size);
});
Source : the excellent article on the topic here : http://www.kavoir.com/2009/01/check-for-file-size-with-javascript-before-uploading.html
Upvotes: 1
Reputation: 30618
When doing file uploads there are a number of things you can check. On the server side, there is also the maximum request size, which will actually stop an upload. But you are correct, the upload will have been already performed by the time either of these checks are caught.
You can now use the HTML5 File API on supported browsers to be cleverer with file uploads, including retrieving the size of them on the client-side, and even displaying previews. See here for an example: Client Checking file size using HTML5?
Upvotes: 2