Ajax AsyncFileUpload Upload Control upload file multiple time - c#

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

Related

indiviual files upload asp.net c#

when i click on link button for adding more file upload then this add only 1 .. means 1 file upload which is already visible and 1 which is display on clicking on linkbutton ..
but when i click again on linkbutton for adding more then this not display ..
i try this
ok i do this
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">upload</asp:LinkButton><br />
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
<asp:Button ID="Button1" runat="server" Text="submit" OnClick="Button1_Click" />
</form>
suppose there is file upload control.. when we select file by clicking on browse and then click on upload then file name with extension i.e. abc.doc should be display ... then when we use again same file upload and click on browse and select another file then file will be display i.e. xyz.pdf.. so there is two files abc.doc and xyz.doc .. so this is want to do .. i want to upload files and display these uploaded files
UPDATE
for this i try this
protected void LinkButton1_Click(object sender, EventArgs e)
{
fileuploadd(FileUpload1.FileName);
}
public void fileuploadd(string filename)
{
try
{
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
SMSEntities s = new SMSEntities();
uploaded_file u = new uploaded_file();
{
u.fileupload = filename;
}
s.uploaded_file.Add(u);
s.SaveChanges();
}
//hpf.SaveAs(Server.MapPath("upload") + "\\" + System.IO.Path.GetFileName(hpf.FileName));
Response.Write("<b>File: </b>" + hpf.FileName + " <b>Size:</b> " + hpf.ContentLength + " <b>Type:</b> " + hpf.ContentType + " Uploaded Successfully <br/>");
}
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
}
so when i select file and click on upload then file name is display .. but when i select again file and click on upload then 1st file name is disappear and 2nd file name is display where as i want both ..
so how i display both filenames ... and when click on submit then record files should be inserted in tables individually i am done with this but not with both filename display at a time ..
Create a FileUpload Control on your .aspx like:
<asp:FileUpload runat="server" ID="UploadImages" AllowMultiple="true" />
then in your code behind:
protected void uploadFile_Click(object sender, EventArgs e)
{
if (UploadImages.HasFiles)
{
foreach (HttpPostedFile uploadedFile in UploadImages.PostedFiles)
{
uploadedFile.SaveAs(System.IO.Path.Combine(Server.MapPath("~/Images/"),
uploadedFile.FileName)); listofuploadedfiles.Text += String.Format("{0}<br />", uploadedFile.FileName);
}
}
}
Multiple File Upload
HI Super User Previously I also had same Problem.
What i Actually did was I have Created 5 File Control's For Example
1) FileUpload1
2) FileUpload2
3) FileUpload3
4) FileUpload4
5) FileUpload5
And I have 4 of them as Hidden on load.
On click of 1 st I am showing 2nd One and on click of 2nd I am showing the 3rd one and So on...
In the Controller/Method I am checking if the File Control is not null then proceeding with the normal File Upload Process By taking Array of File Uploads.
<div id="flOther" runat="server">
<div id="fileOtherUploadarea">
<asp:FileUpload ID="flOtherUPL" runat="server" />
</div>
<input style="width: 20px; border: 0px none; background-color:transparent;" id="btnOtherAddMoreFiles" type="button" onclick="AddOtherMoreImages();" class="icon-plus-sign" />|
<asp:LinkButton ID="lnkOtherUpload" OnCommand="btnLnk_UploadOtherFiles" CommandArgument='<%# Eval("ID") %> 'runat="server">Upload Files</asp:LinkButton>
</div>
<script language="javascript" type="text/javascript">
function AddMoreImages() {
if (!document.getElementById && !document.createElement)
return false;
var fileUploadarea = document.getElementById("fileUploadarea");
if (!fileUploadarea)
return false;
var newLine = document.createElement("br");
fileUploadarea.appendChild(newLine);
var newFile = document.createElement("input");
newFile.type = "file";
newFile.setAttribute("class", "fileUpload");
if (!AddMoreImages.lastAssignedId)
AddMoreImages.lastAssignedId = 100;
newFile.setAttribute("id", "FileUpload" + AddMoreImages.lastAssignedId);
newFile.setAttribute("name", "FileUpload" + AddMoreImages.lastAssignedId);
var div = document.createElement("div");
div.appendChild(newFile);
div.setAttribute("id", "div" + AddMoreImages.lastAssignedId);
fileUploadarea.appendChild(div);
AddMoreImages.lastAssignedId++; }
</script>
protected void btnLnk_UploadOtherFiles(object sender, CommandEventArgs e)
{
int ID;
try
{
if (!String.IsNullOrEmpty(Convert.ToString(e.CommandArgument)))
{
ID = Convert.ToInt32(e.CommandArgument);
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
string fileExtension = System.IO.Path.GetExtension(hpf.FileName);
if (ValidExtesion(fileExtension))
{
int MaxSizeAllowed = Convert.ToInt32(ConfigurationManager.AppSettings["MaxFileSize"]);
if (hpf.ContentLength < MaxSizeAllowed)
{
int lastIndex = Convert.ToInt32(hpf.FileName.LastIndexOf("\\"));
string FileName = DateTime.Now.Millisecond + hpf.FileName.Substring(lastIndex + 1);
string FileName1 = hpf.FileName.Substring(lastIndex + 1);
FileName = FileName.Replace(" ", "");
StringBuilder AncTag = new StringBuilder();
AncTag = AncTag.Append("<a href='Attachments/AMT/'" + FileName + "' target='_blank'>'" + FileName1 + "' </a>");
string strAncTag = AncTag.ToString();
strAncTag = strAncTag.Replace("'", "");
hpf.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "Attachments/AMT/" + FileName);
obj.UploadOtherFiles_ProblemDescription(ID, strAncTag);
}
else
{
}
}
else
{
}
}
}
}
}
catch (Exception ex)
{
ErrorLog objER = new ErrorLog(ex);
}
finally
{
obj = null;
grdPDC.EditIndex = -1;
}
}

FileUpload Control HasFile is always False

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.

ASP. NET Gridview with DataSourceID not binding properly

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;
}

Upload, rename and display the image with Ajax asyncfileupload - ASP.NET

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);
}
}

how can i call javascript functions with ScriptManager.RegisterStartUpScript inside handler.ashx file?

i have a repeater like below :
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("FilePath","~/HandlerForRepeater.ashx?path={0}") %>'><%# Eval("FileName")%></asp:HyperLink>
<br />
<asp:Label ID="Label3" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "FileCreationDate", "{0:tt h:m:s - yyyy/MM/dd}") %>'></asp:Label>
<hr />
</ItemTemplate>
</asp:Repeater>
i have an HandlerForRepeater.ashx for save as dialog like below :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace FileExplorer
{
/// <summary>
/// Summary description for HandlerForRepeater
/// </summary>
public class HandlerForRepeater : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
private HttpContext _context;
private HttpContext Context
{
get
{
return _context;
}
set
{
_context = value;
}
}
public void ProcessRequest(HttpContext context)
{
Context = context;
string filePath = context.Request.QueryString["path"];
filePath = context.Server.MapPath(filePath);
if (filePath == null)
{
return;
}
System.IO.StreamReader streamReader = new System.IO.StreamReader(filePath);
System.IO.BinaryReader br = new System.IO.BinaryReader(streamReader.BaseStream);
byte[] bytes = new byte[streamReader.BaseStream.Length];
br.Read(bytes, 0, (int)streamReader.BaseStream.Length);
if (bytes == null)
{
return;
}
streamReader.Close();
br.Close();
string fileName = System.IO.Path.GetFileName(filePath);
string MimeType = GetMimeType(fileName);
string extension = System.IO.Path.GetExtension(filePath);
char[] extension_ar = extension.ToCharArray();
string extension_Without_dot = string.Empty;
for (int i = 1; i < extension_ar.Length; i++)
{
extension_Without_dot += extension_ar[i];
}
//if (extension == ".jpg")
//{ // Handle *.jpg and
// WriteFile(bytes, fileName, "image/jpeg jpeg jpg jpe", context.Response);
//}
//else if (extension == ".gif")
//{// Handle *.gif
// WriteFile(bytes, fileName, "image/gif gif", context.Response);
//}
if (HttpContext.Current.Session["User_ID"] != null)
{
WriteFile(bytes, fileName, MimeType + " " + extension_Without_dot, context.Response);
}
else
{
System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "MyMethod", "alert('You Can Not Download - pzl Login First');", true);
}
}
private void WriteFile(byte[] content, string fileName, string contentType, HttpResponse response)
{
response.Buffer = true;
response.Clear();
response.ContentType = contentType;
response.AddHeader("content-disposition", "attachment; filename=" + fileName);
response.BinaryWrite(content);
response.Flush();
response.End();
}
private string GetMimeType(string fileName)
{
string mimeType = "application/unknown";
string ext = System.IO.Path.GetExtension(fileName).ToLower();
Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (regKey != null && regKey.GetValue("Content Type") != null)
mimeType = regKey.GetValue("Content Type").ToString();
return mimeType;
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
every thing is ok about this handler , but i want to show an alert to my users if Session["User_ID"] is Null!
so my problem is in below line :
System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "MyMethod", "MyMethod();", true);
and this line has error in this hadler!
how can i call such these javascript methods in HandlerForRepeater.ashx?
thanks in advance
You should be doing that from the page your repeater control is on not the handler. In the code behind for the page with repeater:
if(HttpContext.Current.Session["User_ID"] != null)
{
Response.Redirect("~/HandlerForRepeater.ashx?path={FilePath}");
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "MyMethod", "MyMethod();", true);
}
You can just output the file from that page but trying to stick to your current example as much as possible.

Categories