I am having trouble using FileUpload control, I want to validate image length, size, format etc. and wanted to display it on ImageControl when successfully validated. This I did through another button click's event but I wanted this to be done on client side's 'OK/OPEN' and 'CANCEL' buttons when 'Browse File' window opens. Pls help.
1 Answer
I don't know why peoples are voting negatively this question. It might be a stupid question or I was not explained enough. I m sorry for that. Any way I found the solution.
I was exploring an event when User selects an Image file of FileUpload from 'Browse File' dialog box.
My code is as follows:
<asp:FileUpload ID="imgUpload" runat="server" CssClass="textfield" Width="200px" Height="24px" ToolTip="Browse patient image " />
<asp:ImageButton ID="imgBtn" runat="server" OnClick="imgBtn_Click" ImageUrl="~/IMAGES/Upload-icon.png" Height="24px" ToolTip="Upload patient image" />
Upload means validate the image and put it in a Session variable and display it on Image control. Later when I click save button it Byte[] array gets save into the database.
`
protected void imgBtn_Click(object sender, ImageClickEventArgs e)
{
Byte[] imgByte = null;
const int PROD_IMG_MAX_WIDTH = 130;
const int PROD_IMG_HEIGHT = 130;
imgEmp.Visible = false;
if (imgUpload.HasFile && imgUpload.PostedFile != null && IsFileValid())
{
HttpPostedFile File1 = imgUpload.PostedFile;
imgByte = new Byte[File1.ContentLength];
File1.InputStream.Read(imgByte, 0, File1.ContentLength);
Session["binaryImage"] = imgByte;
System.Drawing.Image UploadedImage = System.Drawing.Image.FromStream(imgUpload.PostedFile.InputStream);
object o = UploadedImage.Size;
if (UploadedImage.Width > PROD_IMG_MAX_WIDTH && UploadedImage.Height > PROD_IMG_HEIGHT && File1.ContentLength > 1048576)
{
DisplayMessage("Size of image is not correct!");
Session["binaryImage"] = null;
imgEmp.ForeColor = System.Drawing.Color.Red;
imgEmp.Font.Size = FontUnit.Medium;
}
else
{
imgEmp.Height = 100;
imgEmp.Width = 90;
imgEmp.Visible = true;
imgEmp.ImageUrl = "~/ADMIN/MASTERS/ImgDisp.aspx";
ViewState["imgUploadedPhotoName"] = imgUpload.FileName;
}
}
else
{
DisplayMessage("Browse valid image!");
imgEmp.Visible = true;
}
}`
Finally i added this script
$(document).ready(function () {
var labelID = $('#<%= imgUpload.ClientID %>');
var uploadBtnId = $('#<%= imgBtn.ClientID %>');
uploadBtnId.css('display','none');
labelID.bind('change', function () {
uploadBtnId.trigger('click');
});
})