ASP.NET: Restrict Dimensions While Uploading Images With The FileUpload Control
I just had to deal with uploading images to my server and had to figure out a way to restrict my users’ uploads to certain dimensions. It’s pretty easy to do, just not entirely intuitive at first. So, I’ll take the guesswork out of it for you 🙂
My project requires that the images be no wider than 190px and must be exactly 190px tall.
First, add a FileUpload control to your form and an upload button:
<asp:FileUpload id="FileUpload1" runat="server" /><asp:Button id="Button1" runat="server" text="Upload" />
Next, I created a generic helper function for all file uploads, but you don’t have to do that. All you need to do is do the following:
Const PROD_IMG_MAX_WIDTH As Integer = 190 Const PROD_IMG_HEIGHT As Integer = 190 Const ABS_PATH as String = "[Your Server's Absolute Path, usually C:\something\weborsomethingelse\yoursite.com]" Dim savePath As String = ABS_PATH & "\images\" 'Create an image object from the uploaded file Dim UploadedImage As System.Drawing.Image = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream) If UploadedImage.Width > PROD_IMG_MAX_WIDTH Or UploadedImage.Height <> PROD_IMG_HEIGHT Then 'whatever fail code you need Else savePath &= FileUpload1.FileName FileUpload1.SaveAs(savePath) End If
And that’s pretty much all there is to it! Of course you can modify it to accept different folders, change the filename, or anything of that sort. The key is really determining the dimensions from the InputStream. Everything else is gravy.
NOTES: The FileUpload control is only available in .NET 2.0. Also, if your FileUpload control is on an AJAX-ified page, you will need to do some trigger fixes, since you can’t upload a file using AJAX, at least not yet (easily). Lastly, you need to make sure that your server will allow you to write to it from the web. If you’re having problems, talk to your host to have them grant you upload/write access to the server.