I have a FileUpload Control in my Asp.Net Webforms Project that doesn't wasn't to run the if(fuPostPhotoCreate.HasFile) { } block.
Here's the relevant aspx page code:
<asp:UpdatePanel ID="upMain" runat="server">
<ContentTemplate>
<div class="form-group">
<label for="txbPostPhotoCreate">Picture</label>
<asp:FileUpload ID="fuPostPhotoCreate" runat="server" ToolTip="Upload Picture" />
<asp:RegularExpressionValidator ID="revPostPhotoCreate" runat="server" ControlToValidate="fuPostPhotoCreate" ValidationExpression="([a-zA-Z0-9\s_\\.\-:])+(.png|.jpg|.jpeg|.gif)$" CssClass="text-danger" ErrorMessage='Please select a valid image format (".png", ".jpg", ".jpeg" or ".gif")' Display="Dynamic" />
</div>
<asp:LinkButton ID="btnCreatePost" runat="server" CssClass="btn btn-success" OnClick="btnCreatePost_Click" CausesValidation="true" ToolTip="Create Post" >
<span class="glyphicon glyphicon-plus"></span>
Create Post
</asp:LinkButton>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnCreatePost" />
</Triggers>
</asp:UpdatePanel>
Then I have the following in the aspx.cs page:
protected void btnCreatePost_Click(object sender, EventArgs e)
{
// (1) Some non relevant code
if (fuPostPhotoCreate.HasFile)
{
// (2) More non relevant code
}
// (3) Final non relevant code
}
My problem is that the fuPostPhotoCreate.HasFile always returns false even when I have uploaded a file and it's in the the fuPostPhotoCreate control. Therefor the non relevant code (2) never gets run (when it should get run when the fuPostPhotoCreate contains a file.
What could I be doing wrong? The non relevant code (1) and (3) does run successfully.
EDIT:
Here is the full code of that button click:
if (!Page.IsValid)
return;
try
{
var post = new Models.EF.Post();
post.DateCreated = DateTime.Now;
post.Title = txbPostTitleCreate.Text;
post.Body = txbPostBodyCreate.Text;
post.IsPublic = cbxPostPublicCreate.Checked;
int postId = efService.CreatePost(post);
gvDisplayPosts.DataBind();
if (fuPostPhotoCreate.HasFile)
{
//? Get filename extension
string fileName = Path.GetFileName(fuPostPhotoCreate.FileName);
string extension = fileName.Substring(fileName.LastIndexOf('.'));
//? Specify the path to save the uploaded file to.
string tempPath = Server.MapPath("~/Uploads/Temp") + "\\" + postId.ToString() + extension;
string savePath = Server.MapPath("~/Uploads/Posts") + "\\" + postId.ToString() + extension;
string saveThumbnailPath = Server.MapPath("~/Uploads/Posts/Thumbnails") + "\\" + postId.ToString() + extension;
#region Remove EXIF Data
var image = System.Drawing.Image.FromFile(tempPath);
if (Array.IndexOf(image.PropertyIdList, 274) > -1)
{
var orientation = (int)image.GetPropertyItem(274).Value[0];
switch (orientation)
{
case 1:
// No rotation required
break;
case 2:
image.RotateFlip(RotateFlipType.RotateNoneFlipX);
break;
case 3:
image.RotateFlip(RotateFlipType.Rotate180FlipNone);
break;
case 4:
image.RotateFlip(RotateFlipType.Rotate180FlipX);
break;
case 5:
image.RotateFlip(RotateFlipType.Rotate90FlipX);
break;
case 6:
image.RotateFlip(RotateFlipType.Rotate90FlipNone);
break;
case 7:
image.RotateFlip(RotateFlipType.Rotate270FlipX);
break;
case 8:
image.RotateFlip(RotateFlipType.Rotate270FlipNone);
break;
}
//This EXIF data is now invalid and should be removed.
image.RemovePropertyItem(274);
}
image.Save(savePath);
image.Dispose();
var tempDir = new DirectoryInfo(Server.MapPath("~/Uploads/Temp"));
foreach (FileInfo file in tempDir.GetFiles())
{
file.Delete();
}
#endregion
//? Convert savePath photo to thumnail and save to saveThumbnailPath
var fullImage = System.Drawing.Image.FromFile(savePath);
var thumbnailImage = new ImageResizer.ImageJob(fullImage, saveThumbnailPath, new ImageResizer.Instructions("width=150;mode=stretch;autorotate=false"));
thumbnailImage.Build();
string dbPathName = "~/Uploads/Posts/" + postId.ToString() + extension;
string dbThumbnailPath = "~/Uploads/Posts/Thumbnails/" + postId.ToString() + extension;
efService.SetPostPath(postId, dbPathName);
efService.SetPostThumbnailPath(postId, dbThumbnailPath);
}
//? Clear Fields
txbPostTitleCreate.Text = string.Empty;
txbPostBodyCreate.Text = string.Empty;
cbxPostPublicCreate.Checked = false;
//? Hide pnlAddPost
pnlAddPost.Visible = false;
}
catch (Exception ex)
{
string errorMessage = ex.Message.ToString();
lblExceptionMessage.Text = errorMessage;
lblExceptionMessage.Visible = true;
}
Note:
I have found that it seems to work if I change the file to be uploaded at least once before submitting.
I have a page that uses a gridview which has a datasourceID declared, the files display correctly. However, whenever i update a photo of the gridview, the gridview does not update correctly, despite the photo in my folders where the gridview retrieves from being updated already. The only way i can get them to retrieve the right photos are if i actually press F5 or reload the project.
The gridview is also inside a updatepanel.
<asp:UpdateProgress ID="UpdateProgress1" AssociatedUpdatePanelID="UpdatePanel1" runat="server">
<ProgressTemplate>
<div class="overlay" align="center">
<div class="over">
<img alt="progress" src="images/loader.gif"/>
Processing... </div>
</div>
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
<ContentTemplate>
<div id="staffList">
<asp:SqlDataSource ID="SqlDataSource1" runat="server" EnableViewState="false" EnableCaching="false" ConnectionString="<%$ ConnectionStrings:Database1Entities %>"
SelectCommand="SELECT * FROM (SELECT Staff.[StaffID], Staff.[StaffName], Staff.[PhoneNo], Staff.[Photo], Staff.[EmpmType], Staff.[AcadStaff], Designation.[DesignationName], Section.[SectionName], Groups.[GroupName], Staff.[InternetAddr], ROW_NUMBER() OVER(ORDER BY Designation.[SortingOrder]) AS Rownum FROM Staff LEFT JOIN Designation ON Designation.[DesignationID] = Staff.[DesignationID] LEFT JOIN Groups ON Groups.[GroupID] = Staff.[GroupID] LEFT JOIN Section ON Section.[SectionID] = Staff.[SectionID] WHERE (Staff.[StaffName] IS NOT NULL)) AS test1 UNION ALL SELECT * FROM (SELECT Staff.[StaffID], Staff.[StaffName], Staff.[PhoneNo], Staff.[Photo], Staff.[EmpmType], Staff.[AcadStaff], Designation.[DesignationName], Section.[SectionName], Groups.[GroupName], Staff.[InternetAddr], ROW_NUMBER() OVER(ORDER BY Designation.[SortingOrder]) AS Rownum FROM Staff LEFT JOIN Designation ON Designation.[DesignationID] = Staff.[DesignationID] LEFT JOIN Groups ON Groups.[GroupID] = Staff.[GroupID] LEFT JOIN Section ON Section.[SectionID] = Staff.[SectionID] WHERE (Staff.[StaffName] IS NULL)) AS test2;"
DeleteCommand="DELETE FROM Staff Where StaffID=#DSid" DataSourceMode="DataSet" CacheKeyDependency="MyCacheDependency">
<DeleteParameters>
<asp:Parameter Name="DSid" Type="String" />
</DeleteParameters>
</asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" HeaderStyle-HorizontalAlign="Left" DataKeyNames="StaffID" CssClass="table table-striped table-condensed" ForeColor="#333333" GridLines="None" DataSourceID="SqlDataSource1" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" AllowPaging="True" PageSize="8" OnPageIndexChanging="GridView1_PageIndexChanging">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<asp:Image ID="Image1" Height="50px" Width="40px" runat="server" ImageUrl='<%# Eval("Photo", "~/StaffPhoto/{0}") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="StaffID" HeaderText="Staff ID" ReadOnly="True" SortExpression="StaffID"/>
<asp:BoundField DataField="StaffName" HeaderText="Staff Name" SortExpression="StaffName"/>
<asp:BoundField DataField="PhoneNo" HeaderText="Ext. No" SortExpression="PhoneNo" />
<asp:BoundField DataField="DesignationName" HeaderText="Designation Name" SortExpression="DesignationName" />
<asp:BoundField DataField="InternetAddr" HeaderText="Email" SortExpression="InternetAddr" />
<%-- <asp:BoundField DataField="EmpmType" HeaderText="Employment Type" />
<asp:BoundField DataField="AcadStaff" HeaderText="Staff Type" />--%>
<asp:CommandField ShowSelectButton="True" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="btndelete" runat="server" OnClick="btndelete_Click" Text="Delete" CommandName="Delete"
ForeColor="Black" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton runat="server" ID="btnUp" OnClick="Update_Click" ForeColor="Black">Update</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<HeaderStyle BackColor="white" Font-Bold="false" ForeColor="black" />
<PagerStyle HorizontalAlign="Center" CssClass="pagination-ys" />
<RowStyle BackColor="white" ForeColor="#333333" />
<FooterStyle BackColor="white" ForeColor="black" />
<SelectedRowStyle BackColor="#E2DED6" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
<EmptyDataTemplate>
<span style="color: red">* No Data Found.</span>
</EmptyDataTemplate>
</asp:GridView>
</div>
<div style="clear: both; height: 50px;">
</div>
</ContentTemplate>
</asp:UpdatePanel>
code behind for pageload binding
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.SelectedIndex = -1;
GridView1.AllowPaging = false;
}
GridView1.DataBind();
GridView1.AllowPaging = true;
}
On Select for row
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
string subgpID = GridView1.SelectedRow.Cells[1].Text;
BllStaff bs = new BllStaff();
string sName = bs.GetStaffName(subgpID);
if (sName == "")
{
ScriptManager.RegisterStartupScript(this, GetType(), "alert", "StaffErrorMessage();", true);
}
else
{
Response.Redirect("StaffListDetails.aspx?staffid=" + subgpID);
}
}
StaffUpdate Page CS
public partial class StaffUpdate : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(Session["UT"] as string))
{
Response.Redirect("~/LoginPage.aspx");
}
lbMessage.Text = "";
string ID = Request.QueryString["staffid"].ToString();
lblSID.Text = ID;
tbStaffID.Text = ID;
if (Session["UT"].ToString() == "Admin")
{
ddlAT.Items.Remove("Admin");
}
if (ID == Session["StaffID"].ToString())
{
if (Session["UT"].ToString() == "Power Admin")
{
//Button1.Visible = true;
OPassword.Attributes.Remove("style");
NPassword.Attributes.Remove("style");
NCPassword.Attributes.Remove("style");
}
}
tbStaffID.ReadOnly = true;
if (!Page.IsPostBack)
{
if (Session["UT"].ToString() != "Power Admin")
{
if (Session["UT"].ToString() != "Admin")
{
ddlAT.Items.Insert(0, new ListItem("Staff", "Staff"));
ddlAT.Enabled = false;
}
else
{
if (ID == Session["StaffID"].ToString()) { ddlAT.Items.Insert(0, new ListItem("Admin", "Admin")); }
else
{
ddlAT.Items.Insert(0, new ListItem("Staff", "Staff"));
ddlAT.Enabled = false;
}
}
}
else
{
if (ID == Session["StaffID"].ToString())
{
ddlAT.Items.Insert(0, new ListItem("Power Admin", "Power Admin"));
ddlAT.Enabled = false;
}
else
{
BllAccount utAc = new BllAccount();
string utAccount = utAc.GetStaffUT(ID);
if (utAccount == "Admin")
{
ddlAT.Items.Insert(0, new ListItem("Admin", "Admin"));
ddlAT.Items.Insert(1, new ListItem("Staff", "Staff"));
}
else
{
ddlAT.Items.Insert(0, new ListItem("Staff", "Staff"));
ddlAT.Items.Insert(1, new ListItem("Admin", "Admin"));
}
}
}
}
}
private string Encrypt(string clearText)
{
string EncryptionKey = "MAKV2SPBNI99212";
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
protected void Button2_Click(object sender, EventArgs e)
{
string SID = tbStaffID.Text;
string oldP = Encrypt(tbPasswordOld.Text);
string newP = tbPasswordNewC.Text;
string ut = ddlAT.SelectedValue;
string fileName = "";
string OID = Request.QueryString["Staffid"].ToString();
if (tbStaffID.Text != "")
{
if (this.ImageFileUpload.HasFile)
{
if (tbPasswordNewC.Text != "" || tbPasswordOld.Text != "")
{ //update id, password, photo and UT
//if (RegularExpressionValidator2.IsValid)
if (tbPasswordNewC.Text != "" && tbPasswordOld.Text != "")
{
string strsql = "select * FROM Account WHERE UserID='" + SID + "' and Password='" + oldP + "'";
DataTable dt = sql.ExecTable(strsql);
if (dt.Rows.Count > 0)
{
try
{
string[] validFileTypes = { "bmp", "gif", "png", "jpg", "jpeg" };
string ext = System.IO.Path.GetExtension(ImageFileUpload.PostedFile.FileName).ToLower();
bool isValidFile = false;
for (int i = 0; i < validFileTypes.Length; i++)
{
if (ext == "." + validFileTypes[i])
{
isValidFile = true;
break;
}
}
if (!isValidFile)
{
lbMessage.ForeColor = System.Drawing.Color.Red;
lbMessage.Text = "* Invalid File. Please upload a File with extension " +
string.Join(", ", validFileTypes);
}
else
{
FileInfo fi = new FileInfo(ImageFileUpload.FileName);
string extion = fi.Extension;
Session["fileEx"] = extion;
fileName = "Ori" + SID + extion;
//create instance for image class
System.Drawing.Image myimg = default(System.Drawing.Image);
//get uploaded image input stream
using (myimg = System.Drawing.Image.FromStream(ImageFileUpload.PostedFile.InputStream))
{
//resize it using thumbnailimage method
int width = myimg.Width;
int height = myimg.Height;
double bthumbWidth = 300 * width / height;
int thumbWidth = Convert.ToInt32(bthumbWidth);
myimg = myimg.GetThumbnailImage(thumbWidth, 300, null, IntPtr.Zero);
MemoryStream str = new MemoryStream();
//Save it in the server images folder
myimg.Save(Server.MapPath("~\\StaffPhoto\\Ori\\" + fileName), myimg.RawFormat);
myimg.Dispose();
//string strFilePath = Server.MapPath("~/StaffPhoto/") + "\\" + fileName;
//this.ImageFileUpload.SaveAs(strFilePath);
imgUpload.ImageUrl = "~/StaffPhoto/Ori/" + fileName;
}
panCrop.Visible = true;
string up = "a";
Session["UpdateP"] = up;
}
}
catch (Exception ex)
{
lbMessage.ForeColor = System.Drawing.Color.Red;
lbMessage.Text = ex.Message + "* The Photo has failed to update. Please try again later!";
}
}
else
{
lbMessage.Text = "* Password Wrong!";
}
}
else
{
lbMessage.Text = "* Both password field must fill in!";
}
}
else //update photo, id and UT
{
try
{
string[] validFileTypes = { "bmp", "gif", "png", "jpg", "jpeg", "ico", "jpe" };
string ext = System.IO.Path.GetExtension(ImageFileUpload.PostedFile.FileName).ToLower();
bool isValidFile = false;
for (int i = 0; i < validFileTypes.Length; i++)
{
if (ext == "." + validFileTypes[i])
{
isValidFile = true;
break;
}
}
if (!isValidFile)
{
lbMessage.ForeColor = System.Drawing.Color.Red;
lbMessage.Text = "* Invalid File. Please upload a File with extension " +
string.Join(", ", validFileTypes);
}
else
{
FileInfo fi = new FileInfo(ImageFileUpload.FileName);
string extion = fi.Extension;
Session["fileEx"] = extion;
fileName = "Ori" + SID + extion;
//create instance for image class
System.Drawing.Image myimg = default(System.Drawing.Image);
//get uploaded image input stream
using (myimg = System.Drawing.Image.FromStream(ImageFileUpload.PostedFile.InputStream))
{
//resize it using thumbnailimage method
int width = myimg.Width;
int height = myimg.Height;
double bthumbWidth = 300 * width / height;
int thumbWidth = Convert.ToInt32(bthumbWidth);
myimg = myimg.GetThumbnailImage(thumbWidth, 300, null, IntPtr.Zero);
MemoryStream str = new MemoryStream();
//Save it in the server images folder
myimg.Save(Server.MapPath("~\\StaffPhoto\\Ori\\" + fileName), myimg.RawFormat);
myimg.Dispose();
//string strFilePath = Server.MapPath("~/StaffPhoto/") + "\\" + fileName;
//this.ImageFileUpload.SaveAs(strFilePath);
imgUpload.ImageUrl = "~/StaffPhoto/Ori/" + fileName;
}
panCrop.Visible = true;
string up = "b";
Session["UpdateP"] = up;
}
}
catch (Exception ex)
{
lbMessage.ForeColor = System.Drawing.Color.Red;
lbMessage.Text = ex.Message + "* The Photo has failed to update. Please try again later!";
}
}
}
else //update password, id and UT
{
if (tbPasswordNewC.Text != "" || tbPasswordOld.Text != "")
{ //update id, password, photo and UT
//if (RegularExpressionValidator2.IsValid)
if (tbPasswordNewC.Text != "" && tbPasswordOld.Text != "")
{
string strsql = "select * FROM Account WHERE UserID='" + SID + "' and Password='" + oldP + "'";
DataTable dt = sql.ExecTable(strsql);
if (dt.Rows.Count > 0)
{
string upMessage = "You are trying to update the information for staff: " + SID;
string no = "3";
Response.Redirect("AlertUpdate.aspx?MessageNO=" + no + "&UpdateMessage=" + upMessage + "&UpdateStaffid=" + SID + "&fileN=" + fileName + "&NewPass=" + newP + "&UserT=" + ut);
}
else
{
lbMessage.Text = "* Password Wrong!";
}
}
else
{
lbMessage.Text = "* Both password field must fill in!";
}
}
else
{
string upMessage = "You are trying to update the information for staff: " + SID;
string no = "4";
Response.Redirect("AlertUpdate.aspx?MessageNO=" + no + "&UpdateMessage=" + upMessage + "&UpdateStaffid=" + SID + "&fileN=" + fileName + "&NewPass=" + newP + "&UserT=" + ut);
}
}
}
else
{
lbMessage.Text = "* Staff ID must be provided";
}
}
private void CheckName()
{
string SID = tbStaffID.Text;
BllStaff bs = new BllStaff();
string sName = bs.GetStaffName(SID);
if (sName == "")
{
Response.Redirect("StaffListAdSearch.aspx");
}
else
{
Response.Redirect("StaffListDetails.aspx?staffid=" + SID);
}
}
protected void btnUpNewP_Click(object sender, EventArgs e)
{
uploadNewP.Visible = true;
uploadNewPD.Visible = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
string staffid = tbStaffID.Text;
string role = ddlAT.SelectedValue;
Response.Redirect("AlertUSuc.aspx?staffid=" + staffid + "&role=" + role);
}
protected void btnCrop_Click(object sender, EventArgs e)
{
string SID = tbStaffID.Text;
string oldP = Encrypt(tbPasswordOld.Text);
string newP = tbPasswordNewC.Text;
string ut = ddlAT.SelectedValue;
string fileName = Path.GetFileName(imgUpload.ImageUrl);
string filePath = Path.Combine(Server.MapPath("~/StaffPhoto/Ori"), fileName);
string cropFileName = "";
string cropFilePath = "";
if (File.Exists(filePath))
{
System.Drawing.Image orgImg = System.Drawing.Image.FromFile(filePath);
System.Drawing.Rectangle CropArea = new System.Drawing.Rectangle(
Convert.ToInt32(X.Value),
Convert.ToInt32(Y.Value),
Convert.ToInt32(W.Value),
Convert.ToInt32(H.Value));
try
{
Bitmap bitMap = new Bitmap(CropArea.Width, CropArea.Height);
using (Graphics g = Graphics.FromImage(bitMap))
{
g.DrawImage(orgImg, new System.Drawing.Rectangle(0, 0, bitMap.Width, bitMap.Height), CropArea, GraphicsUnit.Pixel);
cropFileName = SID + Session["fileEx"];
cropFilePath = Path.Combine(Server.MapPath("~/StaffPhoto"), cropFileName);
bitMap.Save(cropFilePath);
bitMap.Dispose();
string At = ddlAT.SelectedValue;
if (Session["UpdateP"].ToString() == "a")
{
string upMessage = "You are trying to update the information for staff: " + SID;
string no = "1";
Response.Redirect("AlertUpdate.aspx?MessageNO=" + no + "&UpdateMessage=" + upMessage + "&UpdateStaffid=" + SID + "&fileN=" + cropFileName + "&NewPass=" + newP + "&UserT=" + ut + "&DelFile=" + fileName, false);
}
else if (Session["UpdateP"].ToString() == "b")
{
string upMessage = "You are trying to update the information for staff: " + SID;
string no = "2";
Response.Redirect("AlertUpdate.aspx?MessageNO=" + no + "&UpdateMessage=" + upMessage + "&UpdateStaffid=" + SID + "&fileN=" + cropFileName + "&NewPass=" + newP + "&UserT=" + ut + "&DelFile=" + fileName, false);
}
g.Dispose();
}
}
catch (Exception ex)
{
lbMessage.Text = ex.Message;
}
finally {
orgImg.Dispose();
}
}
}
}
AlertUpdate Code Behind sample
string strsql = "select UserType FROM Account WHERE UserID='" + OID + "'";
DataTable dt = sql.ExecTable(strsql);
if (dt.Rows.Count > 0)
{
uStaffA.UpdateAccountbaseOnStaffID(OID, OID, ut);
}
Updateaccountbaseonstaffid
public int UpdateAccountbaseOnStaffID(string staffid, string NStaffId, string ut)
{
StringBuilder sql;
SqlCommand sqlCmd;
int result = 0;
//int newOrderId = 0;
// create order header
SqlConnection conn = dbConn.GetConnection();
sql = new StringBuilder();
sql.AppendLine("UPDATE Account");
sql.AppendLine("SET UserID=#Nid, StaffID=#Nid, UserType=#UserType where StaffID=#Oid");
try
{
conn.Open();
sqlCmd = new SqlCommand(sql.ToString(), conn);
sqlCmd.Parameters.AddWithValue("#Oid", staffid);
sqlCmd.Parameters.AddWithValue("#Nid", NStaffId);
sqlCmd.Parameters.AddWithValue("#UserType", ut);
result = sqlCmd.ExecuteNonQuery();
}
catch (Exception ex)
{
errMsg = ex.Message;
}
finally
{
conn.Close();
}
return result;
}
AlertUpdateSuc
public partial class AlertUpdateSuc : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Request.QueryString["MesNo"].ToString() == "1")
{
Session.Clear();
Response.Redirect("LoginPage.aspx");
}
else if (Request.QueryString["MesNo"].ToString() == "2")
{
Response.Redirect("StaffListAdSearch.aspx");
}
}
}
In short even though the photo updates correctly, the old photo is still being displayed until i refresh the page.
Any ideas will be helpful! thank you!
If you update the image, it does not mean that your gridview also have to be updated. Nothing will be executed itself. You have to make command to be executed. After updating your image you have to call rebinding of your gridview.
Turns out, In order to rebind your photo correctly, what you have to do is to update the Image URL.
However, because our Image URL never changes, what i had to do was add in some data into the URL so that it becomes unique and updates correctly.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Image img = e.Row.FindControl("Image1") as Image;
string url = img.ImageUrl;
string modified = url + "?time=" + DateTime.Now.ToString();
img.ImageUrl = modified;
}
}
By doing what i did above, the Image in the GridView will be updated.
This works for DetailsView as well, by simply doing it this way:
protected void ViewEmployeeDetails_DataBound(object sender, EventArgs e)
{
Image img = ViewEmployeeDetails.FindControl("Image1") as Image;
string url = img.ImageUrl;
string modified = url + "?time=" + DateTime.Now.ToString();
img.ImageUrl = modified;
}
I want to upload the image to web server file and get the path and save it to database.
HTML and Javascript
<img id="imgDisplay" alt="" src="" style="display: none" class="img-thumbnail" />
<ajaxToolkit:AsyncFileUpload OnClientUploadComplete="uploadComplete" runat="server"
ID="AsyncFileUpload1" UploaderStyle="Traditional" CompleteBackColor="White" UploadingBackColor="#CCFFFF"
ThrobberID="imgLoader" OnUploadedComplete="FileUploadComplete" OnClientUploadStarted="uploadStarted" />
<asp:Image ID="imgLoader" runat="server" ImageUrl="~/Images/loader2.gif"
Height="21px" Width="23px" />
<script type="text/javascript">
function uploadStarted() {
$get("imgDisplay").style.display = "none";
}
function uploadComplete(sender, args) {
var imgDisplay = $get("imgDisplay");
imgDisplay.src = "images/loader.gif";
imgDisplay.style.cssText = "";
var img = new Image();
img.onload = function () {
imgDisplay.style.cssText = "height:240px;width:240px";
imgDisplay.src = img.src;
};
img.src = "<%=ResolveUrl(UploadFolderPath) %>" + args.get_fileName();
}
</script>
C# code behind, event file upload complete
protected string UploadFolderPath = "~/Images/";
protected void FileUploadComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string filename = System.IO.Path.GetFileName(AsyncFileUpload1.FileName);
AsyncFileUpload1.SaveAs(Server.MapPath(this.UploadFolderPath) + filename);
}
With code above, I success to do it... But the problem become when I want to rename the file with GUID, the image not appear after upload.
C# code behind
protected string UploadFolderPath = "~/Images/";
protected void FileUploadComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string fileext = System.IO.Path.GetExtension(AsyncFileUpload1.FileName);
string file_id = Guid.NewGuid().ToString();
AsyncFileUpload1.SaveAs(Server.MapPath(this.UploadFolderPath) + file_id + fileext);
}
I realize in the javascript, it will refer to agrs from file upload control. So that means it cannot refer the new file name.
Javascript
img.src = "<%=ResolveUrl(UploadFolderPath) %>" + args.get_fileName();
So I google to find how to paste a value from code behind to javascript. And I found it. Then modified my behind code something like this
protected string UploadFolderPath = "~/Images/";
protected string image = "";
protected void FileUploadComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string fileext = System.IO.Path.GetExtension(AsyncFileUpload1.FileName);
string file_id = Guid.NewGuid().ToString();
AsyncFileUpload1.SaveAs(Server.MapPath(this.UploadFolderPath) + file_id + fileext);
image = this.ResolveUrl(this.UploadFolderPath) + file_id + filename;
}
And the javascript
<script type="text/javascript">
function uploadStarted() {
$get("imgDisplay").style.display = "none";
}
function uploadComplete(sender, args) {
var imgDisplay = $get("imgDisplay");
imgDisplay.src = "images/loader.gif";
imgDisplay.style.cssText = "";
var img = new Image();
img.onload = function () {
imgDisplay.style.cssText = "height:240px;width:240px";
imgDisplay.src = img.src;
};
img.src = "<%=ResolveUrl(image) %>";
}
</script>
Still not appear because the image variable not have a value inside it. How to solved this?
Sorry for my bad english
Nothing issue with your codes, the only problem i see is that since you edited the path you must revert it back to the original values if you retrieve it unless no image will show.
aspx code for fileupload
<ajax:asyncfileupload id="Asyncfileupload1" onclientuploadcomplete="uploadComplete1"
width="350px" runat="server" uploaderstyle="Traditional"
throbberid="Image6" onuploadedcomplete="Asyncfileupload1_UploadedComplete" />
javascript function
function uploadComplete1()
{
window.location = window.location.href;
}
aspx.cs code
protected void Asyncfileupload1_UploadedComplete(object sender, AsyncFileUploadEventArgs e)
{
string name = Asyncfileupload1.FileName;
string[] spi = name.Split('.');
int len = spi.Length;
string type = spi[len - 1];
if (type == "apk" || type == "ipa")
{
if (Asyncfileupload1.PostedFile.ContentLength > 10)
{
string filename = System.IO.Path.GetFileName(Asyncfileupload1.FileName);
string ext = Path.GetExtension(filename);
string newfilename = Path.GetRandomFileName();
newfilename += ext;
Asyncfileupload1.SaveAs(Server.MapPath("~/product_application/") + newfilename);
MobileStoreEntities mse = new MobileStoreEntities();
ProductMast um = new ProductMast();
int loginid = Utility.login_id();
um = mse.ProductMasts.Where(i => i.ProductID == proid).FirstOrDefault();
um.ApplicationFile = "~/product_application/" + newfilename;
int check1 = mse.SaveChanges();
lblDoc.Text = "Old file is available. Want to change? Then Upload";
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "TestAlert", "alert('" + "Size problem." + "');", true);
}
//Response.Redirect("ProductFileUpload.aspx?proid="+HttpUtility.UrlEncode(enc));
//Response.Redirect("ProductFileUpload.aspx");
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "TestAlert", "alert('" + "Must upload doc, docx or pdf file." + "');", true);
}
}
I have ListView that display info from XML and to save to server from FileUpload that are on this ListView. I dont have problem to write to the XML, the problem is on save the FileUpload to folder.
I belive that i have mistake that i not seperate the listview to itemtemplate and insertemplate and edit...It must to? because the title going to correct place on XML, and even file name. but the file not saved to the folder.
For most tests i did - nothing happent after click on "update" BTN. when i add the int "i" to the items[i] somtimes it just update the xml without saving the file, and sometimes i get error of "out of index".
What is wrong?
ASPX code
<h2><asp:Label ID="LBL_number" runat="server" Text='<%#XPath("id") %>'></asp:Label></h2>
<h2>Small Image</h2> <asp:Image Width="100" CssClass="ltr" runat="server" ID="TB_small" ImageUrl='<%# XPath("small_image_url") %>'></asp:Image><asp:FileUpload ID="FU_small" runat="server" />
<br /><br /><br />
<h2>Big Image</h2> <asp:Image Width="300" CssClass="ltr" runat="server" ID="TB_big" ImageUrl='<%#XPath("big_image_url") %>'></asp:Image><asp:FileUpload ID="FU_big" runat="server" />
<br /><br />
<h2>Title</h2> <asp:TextBox runat="server" ID="TB_title" Text='<%#XPath("title") %>'></asp:TextBox>
<br /><br /><br />
<asp:Button CssClass="btn" ID="Button1" CommandArgument='<%#XPath("id") %>' runat="server" OnClick="update" Text="Update" />
<br />
<asp:Button ID="Button3" CssClass="btn" CommandArgument='<%#XPath("id") %>' runat="server" CommandName="del" OnClick="del" Text="מחק" />
<br /><br />
<br /><br />
</ItemTemplate>
</asp:ListView>
<asp:XmlDataSource ID="XDS_data" runat="server"
DataFile="~/App_Data/AM_data.xml" XPath="/Data/datas/data">
</asp:XmlDataSource>
C# Example only with the small file upload.
protected void update(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load(Path.Combine(Request.PhysicalApplicationPath, "App_Data/AM_data.xml"));
Button myButton = (Button)sender;
int i = Convert.ToInt32(myButton.CommandArgument.ToString());
var FU_small1 = (FileUpload)myButton.FindControl("FU_small");
string extenstion_small = System.IO.Path.GetExtension(FU_small1.FileName);
filename_small = Guid.NewGuid().ToString();
FileUpload fu2 = LV_data.Items[i].FindControl("FU_small") as FileUpload;
if (fu2.HasFile == true)
{
fu2.SaveAs(Server.MapPath("~/imgs/data/big" + filename_small.ToString() + extenstion_small.ToString()));
}
var TB_title = (TextBox)myButton.FindControl("TB_title");
string myString3 = TB_title.Text;
XmlElement el = (XmlElement)doc.SelectSingleNode("Data/datas/data[id='" + i + "']");
el.SelectSingleNode("small_image_url").InnerText = "~/imgs/data" + filename_small + extenstion_small;
el.SelectSingleNode("title").InnerText = myString3;
el.SelectSingleNode("big_image_url").InnerText = "~/imgs/data" + filename_big + extenstion_big;
doc.Save(Path.Combine(Request.PhysicalApplicationPath, "App_Data/AM_data.xml"));
Response.Redirect(Request.RawUrl);
}
There are several problems with your update method:
You need to find control inside container, not inside button. *Wrong approach : * var TB_title = (TextBox)myButton.FindControl("TB_title");
There's no guarantee that id will match ListView's item index. *Wrong approach : * FileUpload fu2 = LV_data.Items[i].FindControl("FU_small") as FileUpload;
etc.
I would suggest to change the method to this:
protected void update(object sender, EventArgs e)
{
int index = 0;
XmlDocument doc = new XmlDocument();
doc.Load(Path.Combine(Request.PhysicalApplicationPath, "App_Data/AM_data.xml"));
Button myButton = (Button)sender;
ListViewItem lvwItem = (ListViewItem)myButton.NamingContainer;
FileUpload FU_small1 = myButton.FindControl("FU_small") as FileUpload;
if (FU_small1 != null && int.TryParse(myButton.CommandArgument, out index))
{
string extenstion_small = System.IO.Path.GetExtension(FU_small1.FileName);
filename_small = Guid.NewGuid().ToString();
TextBox TB_title = myButton.FindControl("TB_title") as TextBox;
string myString3 = TB_title!= null ? TB_title.Text : string.Empty;
if (FU_small1.HasFile == true)
{
FU_small1.SaveAs(Server.MapPath("~/imgs/data/small/" + filename_small + extenstion_small));
}
XmlElement el = (XmlElement)doc.SelectSingleNode("Data/datas/data[id='" + index + "']");
el.SelectSingleNode("small_image_url").InnerText = "~/imgs/data/small/" + filename_small + extenstion_small;
el.SelectSingleNode("title").InnerText = myString3;
el.SelectSingleNode("big_image_url").InnerText = "~/imgs/data/big/" + filename_big + extenstion_big;
doc.Save(Path.Combine(Request.PhysicalApplicationPath, "App_Data/AM_data.xml"));
}
Response.Redirect(Request.RawUrl);
}
And here's a test project I have used to test this.
Finnaly, "foreach" solved it
protected void update(object sender, EventArgs e)
{
//Get xml file
XmlDocument doc = new XmlDocument();
doc.Load(Path.Combine(Request.PhysicalApplicationPath, "App_Data/AM_data.xml"));
//Set button for index it later by CommandArgument
Button myButton = (Button)sender;
foreach (ListViewItem item in LV_data.Items)
{
//Findcontrol of 2 fileupload on listview
FileUpload FU_small1 = (FileUpload)item.FindControl("FU_small1");
FileUpload FU_big1 = (FileUpload)item.FindControl("FU_big1");
//Check if are has file.
if (FU_small1.HasFile && FU_big1.HasFile)
{
//Get extension and genereate random filenames (for avoid ovveride)
FileInfo small_info = new FileInfo(FU_small1.FileName);
FileInfo big_info = new FileInfo(FU_big1.FileName);
string ext_small = small_info.Extension;
string ext_big = big_info.Extension;
string filename_small = Guid.NewGuid().ToString();
string filename_big = Guid.NewGuid().ToString();
//Set i value by button CommandArgument (look on aspx on question)
int i = Convert.ToInt32(myButton.CommandArgument.ToString());
//Get title from TextBox and set string from it
TextBox TB_title = myButton.FindControl("TB_title") as TextBox;
string myString3 = TB_title != null ? TB_title.Text : string.Empty;
//Save the files from the fileuploads we found, and write it on xml
FU_small1.SaveAs(Path.Combine(Request.PhysicalApplicationPath, "imgs/data/thumbs/" + filename_small + ext_small));
FU_big1.SaveAs(Path.Combine(Request.PhysicalApplicationPath, "imgs/data/big/" + filename_big + ext_big));
XmlElement el = (XmlElement)doc.SelectSingleNode("Data/datas/data[id='" + i + "']");
el.SelectSingleNode("small_image_url").InnerText = "~/imgs/data/thumbs/" + filename_small + ext_small;
el.SelectSingleNode("title").InnerText = myString3;
el.SelectSingleNode("big_image_url").InnerText = "~/imgs/data/big/" + filename_big + ext_big;
doc.Save(Path.Combine(Request.PhysicalApplicationPath, "App_Data/AM_data.xml"));
}
}
// Refresh the page
Response.Redirect(Request.RawUrl);
}
I have been trying to sort this issue for the whole day so far I have no luck. I have a Web Form which has some asp.net form controls and Two AsyncFileUpload controls. When I upload the image using first AsyncFileUpload1, it uploads only one image and when I upload the second image using AsyncFileUpload2 it uploads two versions of the same image.
Things go crazy when I click the Save Button to save data it then upload 3 more version of the images in total sometime 6 or more. I have tried different way and have finally given up.
Sample code in HTML FILE
<script type = "text/javascript">
function uploadComplete(sender) {
// $get("<%=lblImageUploadMessage1.ClientID%>").innerHTML = "File Uploaded Successfully";
// $get("<%=lblImageUploadMessage2.ClientID%>").innerHTML = "File Uploaded Successfully";
clearContents();
clearContents2();
}
function uploadError(sender) {
// $get("<%=lblImageUploadMessage1.ClientID%>").innerHTML = "File upload failed. only Image files are allowed";
// $get("<%=lblImageUploadMessage2.ClientID%>").innerHTML = "File upload failed. only Image files are allowed";
clearContents();
}
</script>
<script type = "text/javascript">
function clearContents() {
var span = $get("<%=AsyncFileUpload1.ClientID%>");
var txts = span.getElementsByTagName("input");
for (var i = 0; i < txts.length; i++) {
if (txts[i].type == "text") {
txts[i].value = "";
}
}
}
function clearContents2() {
var span = $get("<%=AsyncFileUpload2.ClientID%>");
var txts = span.getElementsByTagName("input");
for (var i = 0; i < txts.length; i++) {
if (txts[i].type == "text") {
txts[i].value = "";
}
}
}
window.onload = clearContents;
</script>
<div class="row">
<asp:Label ID="lblPageTitleE" CssClass="txtLabel" runat="server" Text="Page Title (E) :"></asp:Label>
<asp:TextBox ID="txtPageTitleE" runat="server" CssClass="txtbox700"></asp:TextBox>
<asp:RequiredFieldValidator ID="RFVPageTitleE" runat="server" ErrorMessage="*"
ControlToValidate="txtPageTitleE" ValidationGroup="atpAddNewPage" CssClass="validation"></asp:RequiredFieldValidator>
</div>
<div class="row">
<asp:Label ID="lblPageTitleA" CssClass="txtLabel" runat="server" Text="Page Title (A) :"></asp:Label>
<asp:TextBox ID="txtPageTitleA" runat="server" CssClass="txtbox700"></asp:TextBox>
<asp:RequiredFieldValidator ID="RFVPageTitleA" runat="server" ErrorMessage="*"
ControlToValidate="txtPageTitleA" ValidationGroup="atpAddNewPage" CssClass="validation"></asp:RequiredFieldValidator>
</div>
<!-- Image Control -->
<div class="row">
<asp:Label ID="lblBannerImageE" CssClass="txtLabel" runat="server" Text="Banner Image (E) :"></asp:Label>
<asp:AsyncFileUpload OnClientUploadError="uploadError" OnClientUploadComplete="uploadComplete"
runat="server" ID="AsyncFileUpload1" UploaderStyle="Modern" CompleteBackColor="White"
UploadingBackColor="#336699" ThrobberID="imgLoader" OnUploadedComplete="AsyncFileUpload1_UploadedComplete" CssClass="AFU2" Width="400px" />
<asp:Label ID="lblImageUploadMessage1" CssClass="imgLabel" runat="server" Text=""></asp:Label>
<asp:Image ID="imgLoader" runat="server" ImageUrl="~/images/ajax-loader-small.gif" />
</div>
<div class="row">
<asp:Label ID="lblBannerImageA" CssClass="txtLabel" runat="server" Text="Banner Image (A) :"></asp:Label>
<asp:AsyncFileUpload OnClientUploadError="uploadError" OnClientUploadComplete="uploadComplete"
runat="server" ID="AsyncFileUpload2" UploaderStyle="Modern" CompleteBackColor="White"
UploadingBackColor="#336699" ThrobberID="imgLoader2" OnUploadedComplete="AsyncFileUpload2_UploadedComplete" CssClass="AFU2" Width="400px" />
<asp:Label ID="lblImageUploadMessage2" CssClass="imgLabel" runat="server" Text=""></asp:Label>
<asp:Image ID="imgLoader2" runat="server" ImageUrl="~/images/ajax-loader-small.gif" />
</div>
<!-- Image Control -->
Below is the sample code of .CS file
In this file i am assigning each image unique name using GUID and image upload AsyncFileUpload code gets execute multiple times and i am not able to figure out i am so confused now.
public partial class _Default : System.Web.UI.Page
{
String BannerImageNameEn, BannerImageNameAr;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Session["BannerImageNameEn"] = "Null";
//Session["BannerImageNameEn"] = "Null";
}
}
protected void btnCreatePage_Click(object sender, EventArgs e)
{
BusinessLogic objBLAddNewPage = new BusinessLogic();
Pages objPages = new Pages();
objPages.PageNameEn = txtPageNameE.Text;
objPages.PageNameAr = txtPageNameA.Text;
objPages.PageTitleEn = txtPageTitleE.Text;
objPages.PageTitleAr = txtPageTitleA.Text;
objPages.PageDescEn = txtPageDescE.Text;
objPages.PageDescAr = txtPageDescA.Text;
objPages.PageKeywordEn = txtPageKeywordsE.Text;
objPages.PageKeywordAr = txtPageKeywordsA.Text;
objPages.PageBodyEn = CKEditorPageBodyE.Text;
objPages.PageBodyAr = CKEditorPageBodyA.Text;
objPages.PageLinkPositionNo = int.Parse(txtPageLinkPosition.Text);
objPages.PageLayoutPosition = ddPageLayoutPosition.SelectedItem.Value.ToString();
// Assign Name to Images
objPages.PageBannerImageEn = Session["BannerImageNameEn"].ToString();
objPages.PageBannerImageAr = Session["BannerImageNameAr"].ToString();
objPages.PageBannerLinkEn = txtBannerLinkEnglish.Text;
objPages.PageBannerLinkAr = txtBannerLinkArabic.Text;
objPages.PageWindow = ddPageWindow.SelectedItem.Value.ToString();
objPages.PageActive = bool.Parse(ddPageActive.SelectedItem.Value.ToString());
objPages.PageVisible = bool.Parse(ddPageHidden.SelectedItem.Value.ToString());
objPages.PageCreateDate = Helper.GetUAEDateTime();
objPages.PageUpdateDate = Helper.GetUAEDateTime();
objPages.PageIPAddress = Request.ServerVariables["REMOTE_ADDR"];
try
{
bool result;
//result = objBLAddNewPage.CreateNewPage(objPages);
result = false;
if (result == true)
{
Response.Redirect("PageCreated.aspx");
}
else
{
}
}
catch (Exception ex)
{
//lblresult.Text = ex.ToString();
}
}
protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
try
{
String filePath = string.Empty;
String CurrentGUID = Guid.NewGuid().ToString();
if (AsyncFileUpload1.HasFile)
{
string filename = System.IO.Path.GetFileName(AsyncFileUpload1.FileName);
System.IO.FileInfo f = new System.IO.FileInfo(AsyncFileUpload1.PostedFile.FileName);
int fileSize = Int32.Parse(System.IO.Path.GetFileName(e.FileSize));
if (fileSize < 1024000) // 1 MB current size size in bytes 102400=100kb 512000 = 500kb
{
if ((f.Extension.ToLower() == ".jpg") || (f.Extension.ToLower() == ".png") || (f.Extension.ToLower() == ".gif") || (f.Extension.ToLower() == ".jpeg"))
{
filename = CurrentGUID + f.Extension;
//string productGUID
filePath = Server.MapPath("../ImageUploads/") + filename;
if (System.IO.File.Exists(filePath))
{
return;
}
else
{
//Upload files
AsyncFileUpload1.PostedFile.SaveAs(Server.MapPath("../ImageUploads/") + filename);
Session["BannerImageNameEn"] = filename.ToString();
string errMsg = "File Uploaded Successfully";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "size", "top.$get(\"" + lblImageUploadMessage1.ClientID + "\").innerHTML='" + errMsg + "';", true);
// ResizeImage(string OriginalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)
Helper.ResizeImage(filePath, filePath, 150, 80, true);
}
return;
}
}
else
{
lblImageUploadMessage1.Text = "Only type .jpg, .png, .gif are allow";
string errMsg = "File must be an Image type of .jpg, .png, .gif, .jpeg";
//client-side error
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "size", "top.$get(\"" + lblImageUploadMessage1.ClientID + "\").innerHTML='" + errMsg + "';", true);
return;
}
}
else
{
//lblMesg.Text = "Only type .jpg, .png, .gif are allow";
string errMsg = "File size is greater the 1MB";
//client-side error
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "size", "top.$get(\"" + lblImageUploadMessage1.ClientID + "\").innerHTML='" + errMsg + "';", true);
return;
}
}
catch (Exception ex)
{
}
}
protected void AsyncFileUpload2_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
try
{
String filePath = string.Empty;
String CurrentGUID = Guid.NewGuid().ToString();
if (AsyncFileUpload1.HasFile)
{
string filename = System.IO.Path.GetFileName(AsyncFileUpload1.FileName);
System.IO.FileInfo f = new System.IO.FileInfo(AsyncFileUpload1.PostedFile.FileName);
int fileSize = Int32.Parse(System.IO.Path.GetFileName(e.FileSize));
if (fileSize < 1024000) // 1 MB current size size in bytes 102400=100kb 512000 = 500kb
{
if ((f.Extension.ToLower() == ".jpg") || (f.Extension.ToLower() == ".png") || (f.Extension.ToLower() == ".gif") || (f.Extension.ToLower() == ".jpeg"))
{
filename = CurrentGUID + f.Extension;
//string productGUID
filePath = Server.MapPath("../ImageUploads/") + filename;
if (System.IO.File.Exists(filePath))
{
return;
}
else
{
//Upload files
AsyncFileUpload2.PostedFile.SaveAs(Server.MapPath("../ImageUploads/") + filename);
Session["BannerImageNameAr"] = filename.ToString();
string errMsg = "File Uploaded Successfully";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "size", "top.$get(\"" + lblImageUploadMessage2.ClientID + "\").innerHTML='" + errMsg + "';", true);
// ResizeImage(string OriginalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)
Helper.ResizeImage(filePath, filePath, 150, 80, true);
}
return;
}
}
else
{
lblImageUploadMessage1.Text = "Only type .jpg, .png, .gif are allow";
string errMsg = "File must be an Image type of .jpg, .png, .gif, .jpeg";
//client-side error
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "size", "top.$get(\"" + lblImageUploadMessage2.ClientID + "\").innerHTML='" + errMsg + "';", true);
return;
}
}
else
{
//lblMesg.Text = "Only type .jpg, .png, .gif are allow";
string errMsg = "File size is greater the 1MB";
//client-side error
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "size", "top.$get(\"" + lblImageUploadMessage2.ClientID + "\").innerHTML='" + errMsg + "';", true);
return;
}
}
catch (Exception ex)
{
}
}
}
I simply want a functionality where i can upload two images assign them unique name using GUID and finally same the image name along with the other form data in the database.
I am using ASP.NET, C# 3.0 and Framework 4, Latest version of Ajax downloaded today And i have to do assignment in ASP.Net only