indiviual files upload asp.net c# - 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;
}
}

Related

Windows Media Player in ASP.NET C#

First attempt at this: I created the Windows Media Player programmatically by adding the WMPLib as a reference in my project. I am trying to play a playlist using Windows Media Player in a ASP.Net web page (Visual Studio 2015). I cannot use the video tag used in examples for HTML 5 as I need to display .wmv, .mp4, .jpg formats in the control. When I run the code, no errors are displayed and I see an empty browser, what am I missing?
Here is my sample code:
WMPLib.WindowsMediaPlayer Player;
protected void Page_Load(object sender, EventArgs e)
{
FileNames();
}
public void FileNames()
{
String[] extentions = { "*.wmv", "*.mp4", "*.jpg" };
List<string> files = new List<string>();
foreach (string filter in extentions)
{
files.AddRange(System.IO.Directory.GetFiles(#"C:\Documents\", filter));
}
foreach (string ss in files)
{
String name = System.IO.Path.GetFileName(ss);
Player = new WMPLib.WindowsMediaPlayer();
WMPLib.IWMPPlaylist playList = Player.newPlaylist("myPlayList", "");
playList.appendItem(Player.newMedia(name));
Player.currentPlaylist = playList;
Player.controls.play();
}
}
I am aware of the hard coded path which is not good practice, however I just need to get this displaying on my local machine.
Thanks!
After two more weeks of research we managed to come up with a solution by toggling between different types of controls based on the content that needs to be displayed. To display PowerPoint slideshows, we converted all slides to images and then looped through the collection. Here is a snippet of the code in case someone else needs a bit of guidance with a similar issue:
<body>
<form id="form1" runat="server">
<%-- Video DIV --%>
<div runat="server" id="VidDiv" class="fullscreen-bg">
</div>
<%-- IMAGE DIV --%>
<div runat="server" id="container">
<div runat="server" id="containers">
</div>
<%-- this is where the code gets dynamically created --%>
</div>
</form>
</body>
<script src="Scripts/jquery-3.1.1.js"></script>
<script id="CallMyFunction" type="text/javascript">
var index = 1;
document.getElementById("VidDiv").style.display = "none";
var ImageCount = 1;
autoSlide();
function autoSlide() {
var x = document.getElementsByClassName("Images");
var video_player = document.getElementsByClassName("fullscreen-bd__video");
var count;
var video;
var videoSource = new Array(), vids, i;
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
if (index > x.length) {
index = 1
}
x[index - 1].style.display = "block";
count = x.length;
if (ImageCount <= count) {
index++;
ImageCount = 1 + ImageCount;
setTimeout(autoSlide, 8000);
}
else {
//this is where we should switch from image div to video div
document.getElementById("container").style.display = "none";
document.getElementById("VidDiv").style.display = "block";
//create a counter to check the number of video tags
video = document.getElementsByTagName('video'), numVideos = video.length;
for (i = 0; i < numVideos; i++) {
videoSource[i] = video.item(i).src;
document.getElementById("myVideo" + i).style.display = "none";
}
var videoCount = 0;
if (videoCount <= numVideos -1) {
function videoPlay(videoNum) {
if (videoCount > 0)
{
document.getElementById("myVideo" + (videoCount - 1)).style.display = "none";
}
document.getElementById("myVideo" + videoCount).style.display = "block";
document.getElementById("myVideo" + videoCount).setAttribute("src", "" + videoSource[videoCount] + "");
document.getElementById("myVideo" + videoCount).load();
document.getElementById("myVideo" + videoCount).play();
onEndedVid = document.getElementById("myVideo" + videoCount);
var onEndedVid;
onEndedVid.onended = function () {
//at the end of the video, close full screen
myHandler();
};
videoCount = videoCount + 1;
}
function myHandler() {
if (videoCount == numVideos) {
//this is where we should switch from image div to video div
document.getElementById("container").style.display = "none";
document.getElementById("VidDiv").style.display = "none";
location.reload();
}
else {
videoPlay(videoCount);
}
}
myHandler();
}
else
{
///back to images
//refresh the page
location.reload();
}
}
}
Code behind:
// this will be a watcher that checks if is new content... if there is, delete the existing .wpl file and recreate the .wpl with new content links included
private void CreateNewPlayList(string folder)
{
try
{
System.Threading.Thread.Sleep(5000);
fileName = getDrive(folder) + #"\" + folder + "Playlist.wpl";
FileInfo fileInfo = new FileInfo(fileName);
String f = #"<?wpl version=""1.0""?>
<smil>
<head><meta name=""Generator"" content=""Microsoft Windows Media
Player -- 10.0.0.3646""/>
<author/>
<title> a title goes here </title>
</head>
<body>
<seq> ";
String ff = #"
</seq>
</body>
</smil>";
using (FileStream fs = fileInfo.Create())
{
Byte[] txt = new UTF8Encoding(true).GetBytes(f);
fs.Write(txt, 0, txt.Length);
////write paths and load only certain file types according to requirements into array
String[] extentions = { "*.mp4", "*.wmv", "*.JPG".ToLower(), "*.ppt", "*.png" };
List<string> files = new List<string>();
foreach (string filter in extentions)
{
files.AddRange(System.IO.Directory.GetFiles(getDrive(folder) + #"\", filter));
}
int filecount = files.Count;
string[] video_lists = new string[files.Count];
int counts = 0;
foreach (string file in files)
{
video_lists[counts] = file.ToString();
string PathfileName = Path.GetFileName(file);
Byte[] author;
//use the ppt to be able to go into the folder and add each slide as part of the playlist
if (Path.GetExtension(PathfileName) == ".ppt" || Path.GetExtension(PathfileName) == ".pptx")
{
//create a loop to loop through the folder that has the same name as ppt/pptx(PathFileName)
string pptDrive = getDrive(folder) + #"\" + Path.GetFileNameWithoutExtension(PathfileName) + #"\";
if (Directory.Exists(pptDrive))
{
string[] pptFilesFolder = Directory.GetFiles(pptDrive);
int counter = 1;
while (counter <= pptFilesFolder.Length)
{
foreach (string pptFile in pptFilesFolder)
{
string pptFileName = Path.GetFileName(pptFile);
string pptFileNameNoExt = Path.GetFileNameWithoutExtension(pptFile);
int i = pptFilesFolder.Length;
int ss = Convert.ToInt16(new String(pptFileNameNoExt.Where(Char.IsDigit).ToArray()));
if (ss <= i && ss == counter)
{
author = new UTF8Encoding(true).GetBytes(#"<media src=""" + pptDrive + #"\" + pptFileName + "\"/>");
fs.Write(author, 0, author.Length);
counter++;
}
}
}
}
else
{
//do something...
}
}
else
{
author = new UTF8Encoding(true).GetBytes(#"<media src=""" + getDrive(folder) + #"\" + PathfileName + "\"/>");
fs.Write(author, 0, author.Length);
}
counts = counts + 1;
}
Byte[] toptxt = new UTF8Encoding(true).GetBytes(ff);
fs.Write(toptxt, 0, toptxt.Length);
}
}
catch (IOException io)
{
//error handling....
return;
}
catch (Exception ex)
{
//error handling...
return;
}
}
The code can obviously be improved and optimized, but this is the base we used to get our app working. Thanks for all the advice and input!

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.

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

FileUpload on listview

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

Ajax AsyncFileUpload Upload Control upload file multiple time

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

Categories