1. Placing the FileUpload object
First, we need to set the FileUpload object, we will use the one .Net gives us:
<asp:FileUpload ID="myFile" runat="server" />
That was easy 🙂
2. Getting the file from the FileUpload object
2.1 Checking the uploaded file is an image
Before going on, I want to show you this useful function you will need later:
public Boolean IsImage(HttpPostedFile pf) { Boolean res = false; switch (pf.ContentType) { case "image/gif": case "image/jpeg": case "image/jpg": case "image/bmp": case "image/png": case "image/pjpeg": case "image/x-png": res = true; break; default: res = false; break; } if (!res) { //If the filetype doesnt work i try with the extension: switch (Path.GetExtension(pf.FileName)) { case "gif": case "jpeg": case "jpg": case "bmp": case "png": res = true; break; default: break; } } return res; }
2.2 Checking Im uploading something
I like to have these two useful methods:
private Boolean IsUploadingAnImage() { return (myFile.PostedFile != null && myFile.PostedFile.FileName != ""); } private void UploadPhoto() { MyNamespace.Uploads.UploadProfileImage(myFile); // A call to a class that will do the stuff (see below) // Do more stuff if necessary }
So I can do this:
if (IsUploadingAnImage()) { UploadPhoto(); }
2.3 Getting the file
To get the file in the object you need a byte array to get the input, then you can use that array to save it into the db, to create a file and save it in disk or to create an image object and play with it before doing something else. Lets see:
// Getting the object into a byte array: byte[] fileData = new byte[Uploader.PostedFile.ContentLength]; //We make a byte array with the file size. Uploader.PostedFile.InputStream.Read(fileData, 0, (int)Uploader.PostedFile.ContentLength); //we read the file into our array.
Saving it into the database
Putting all of it together and using a stored that saves the image into db with its type.
public void UploadProfileImage(FileUpload Uploader) { if (IsImage(Uploader.PostedFile)) { byte[] fileData = new byte[Uploader.PostedFile.ContentLength]; //We make a byte array with the file size. Uploader.PostedFile.InputStream.Read(fileData, 0, (int)Uploader.PostedFile.ContentLength); //we read the file into our array. List<SqlParameter> pl = new List<SqlParameter>(); pl.Add(new SqlParameter("image", fileData)); pl.Add(new SqlParameter("mimeType", Uploader.PostedFile.ContentType)); IDataReader dr = MyNamespace.db.getReader("sp_UploadImage", pl); if (dr != null && dr.Read()) { if (dr[0].ToString().ToUpper() == "OK") { ImageID = (int)dr[1]; // I could get the new image id in db, for example. } } } else { ErrorMessage = "File must be an image."; } }