Displaying image using Image control in button click event - asp.net

I am creating image comparison (images exists in directory) web based application. It compares images exists in particular directory with provided image. It compares each image with matching percentage but not displaying images from related directory even i have given the image url to that images also. When i write response.write then it shows matching percentage with that matching image, but not displaying images.
I have written code for that as follows :
protected void btnnew_Click(object sender, EventArgs e)
{
Bitmap searchImage;
try
{
//Image for comparing other images that are exists in directory
searchImage = new Bitmap(#"D:\kc\ImageCompare\Images\img579.jpg");
}
catch (ArgumentException)
{
return;
}
string dir = "D:\\kc\\ImageCompare\\Images";
DirectoryInfo dir1 = new DirectoryInfo(dir);
FileInfo[] files = null;
try
{
files = dir1.GetFiles("*.jpg");
}
catch (DirectoryNotFoundException)
{
Console.WriteLine("Bad directory specified");
return;
}
double sim;
foreach (FileInfo f in files)
{
sim = Math.Round(GetDifferentPercentageSneller(searchImage, new Bitmap(f.FullName)), 3);
if (sim >= 0.95)
{
Image1.ImageUrl = dir + files[0];
Image2.ImageUrl = dir + files[1];
Response.Write("Perfect match with Percentage" + " " + sim + " " + f);
Response.Write("</br>");
}
else
{
Response.Write("Not matched" + sim);
}
}
}

ASP.NET pages follows control based development - so generally, you don't directly write to a response but rather update text for control such as label or literal.
As far as image goes, for image to visible in the browse, you need to set the url that is accessible from the browser. In above code, you are setting the physical file path and which is not going to be accessible as a URL from same/different machine. You need either to map a virtual directory to your image storage location and then generate a url for the same (by appending virtual directory path & file name) or to write a file serving handler (ashx) that would take the image partial path and serve the image (i.e. send its data to browser).

Related

Trying to Create a Folder, but it creates in different location

In my ASP.NET WEbForms app, I want to create a folder and save files in it. In my project I have a folder named CRMImages/Projects. I want to create a sub folder in Projects folder & save images from their. Currently I retrieve images from CRMImages/ as the parent folder.
This is my code that I have on code-behind :
try
{
string pathToCreate = "~/CRMImages/Projects/" + item.ProjectId;
string myFileName = "";
if (!Directory.Exists(Server.MapPath(pathToCreate)))
{
DirectoryInfo di = Directory.CreateDirectory(pathToCreate);
var user = System.Security.Principal.WindowsIdentity.GetCurrent().User;
var userName = user.Translate(typeof(System.Security.Principal.NTAccount));
System.Security.AccessControl.DirectorySecurity sec = di.GetAccessControl();
sec.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(userName,
System.Security.AccessControl.FileSystemRights.Modify,
System.Security.AccessControl.AccessControlType.Allow));
di.SetAccessControl(sec);
Directory.CreateDirectory(pathToCreate);
System.Diagnostics.Debug.WriteLine("FOLDER CREATED PATH : " + di.FullName);
myFileName = pathToCreate + "/projectLogo.png";
System.Diagnostics.Debug.WriteLine("PATH To Save Logo File & NAME : " + myFileName);
/*
if (File.Exists(item.ProjectLogoUrl) ) {
FileUpload projLogoUpload = new FileUpload();
if (projLogoUpload.HasFile) {
myFileName = pathToCreate + "/projectLogo.png";
projLogoUpload.SaveAs(myFileName);
}
// panFileBtn.SaveAs(filePath);
} */
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("EXCEPTION While SAving File : " + ex.Message + "\n *** STACK" + ex.StackTrace);
}
The code executes, but I don't see the folder created in my project folder. Lets say the value of item.ProjectId is "EMP3", the logs that I see on the above code execution is :
FOLDER CREATED PATH : C:\Program Files (x86)\IIS Express\~\CRMImages\Projects\EMP3
PATH To Save Logo File & NAME : ~/CRMImages/Projects/EMP3/projectLogo.png
I checked in IIS Express folder & there this full path is created. Can you say why is it saving in IISExpress & how to create the folder in the /CRMImages/Projects folder that already exists in my project !!
Any help is highly appreciated.
Thanks
You have to replace below line
DirectoryInfo di = Directory.CreateDirectory(pathToCreate);
With
DirectoryInfo di = Directory.CreateDirectory(Server.MapPath(pathToCreate));

How to find filebytes of individual uploaded files in asp.net?

I am implementing the multiple file upload through asp.net fileupload control & saving uploaded files to database. While iterating the files, I am trying to set the Data property of File class. For single file, I can set it as File.Data = postedFile.FileBytes.
But, while iterating files, FileBytes property value getting set everytime similar.
Can anybody explain what could be the reason? How can I implement it?
code sample:
if (fuAttachment.HasFiles)
{
foreach (HttpPostedFile postedFile in fuAttachment.PostedFiles)
{
DataAccess.File file = new DataAccess.File();
file.Data = fuAttachment.FileBytes;//not working for multiple files.
}
}
Remember, a file upload control still posts files behind the scenes.
here is basically how to retrieve multiple files, this works with one and/or multiple file upload controls, and counts ALL the posted files in ALL of the upload controls:
HttpFileCollection uploadedFiles = Request.Files;
for (int i = 0; i < uploadedFiles.Count; i++)
{
HttpPostedFile userPostedFile = uploadedFiles[i];
try
{
if (userPostedFile.ContentLength > 0)
{
//do stuff with your file, check the attributes and functions of 'userPostedFile' to see what you can get from it, there is an input stream as well as file name among everything else.
}
}
catch (Exception Ex)
{
//here do stuff if file upload fails, adjust exception type as needed.
}
}

How do I upload a file to an Acumatica Screen through HTTP virtual path?

How do I upload a file to an Acumatica Screen through HTTP virtual path?
For example, I would like to upload mysite.com/files/abc.pdf to the Sales orders screen.
Below is a code snippet to achieve your goal.It is reading file from HTTP URL and attaching it to one of the existing Case.
//Graph for file management
PX.SM.UploadFileMaintenance filegraph = PXGraph.CreateInstance<PX.SM.UploadFileMaintenance>();
//Since you need file from HTTP URL - below is a sample
WebRequest request = WebRequest.Create("http://www.pdf995.com/samples/pdf.pdf");
using (System.IO.Stream dataStream = request.GetResponse().GetResponseStream())
{
using (System.IO.MemoryStream mStream = new System.IO.MemoryStream())
{
dataStream.CopyTo(mStream);
byte[] data = mStream.ToArray();
//Create file info, you may check different overloads as per your need
PX.SM.FileInfo fileinfo = new PX.SM.FileInfo("case.pdf", null, data);
if (filegraph.SaveFile(fileinfo))
{
if (fileinfo.UID.HasValue)
{
// To attach the file to case screen - example
CRCaseMaint graphCase = PXGraph.CreateInstance<CRCaseMaint>();
//Locate existing case
graphCase.Case.Current = graphCase.Case.Search<CRCase.caseCD>("<Case to which you want to attach file>");
//To Attach file
PXNoteAttribute.SetFileNotes(graphCase.Case.Cache, graphCase.Case.Current, fileinfo.UID.Value);
//To Attach note
PXNoteAttribute.SetNote(graphCase.Case.Cache, graphCase.Case.Current, "<Note you wish to specify>");
//Save case
graphCase.Save.Press();
}
}
}
}

Fileupload saveas method doesn't overwrite

I have a very simple requirement, there's a folder containing an image file, I have a form with only one upload field to select an image and save it with the same existing image name to overwrite it
protected void ChangeLogo(object sender, EventArgs e)
{
if (!ImageUpload.HasFile)
{
ShowPopup("Logo Upload Canceled", "Please upload the image for the logo.", "stop");
}
else //save the image
{
string logoPath = Server.MapPath("~/images/home/");
string filename = "logo.png";
ImageUpload.SaveAs(logoPath + filename);
}
}
I am getting an error:
Access to the path 'C:\inetpub\wwwroot\website\images\home\logo.png' is denied
even though there's full access control on the folder but if i saved it with a different name it works, it only refuses to overwrite and I need to overwrite. I thought of first deleting the image then saving, but this is silly, why can't I overwrite?
Thanks in advance
Naive solution:
If(File.Exists(logoPath + filename))
File.Delete(logoPath + filename);
ImageUpload.SaveAs(logoPath + filename);

How to work with FileUpload in a WebPage?

I have follow code in a ASP.Net Webpage:
protected void btnSend_Click(object sender, EventArgs e)
{
string imei = Request.QueryString["id"];
int imeiID = int.Parse(imei);
if (fuPicture.HasFile)
{
fuPicture.SaveAs("/Images/" + imei + ".jpg");
DAL.ImeiHandling.SavePicture(imeiID, "");
}
string code = Request.QueryString["code"];
Response.Redirect("~/UploadPicture.aspx?id=" + imei + "&code=" + code);
}
How to fill the SaveAs and how to load the path in a ASP:Image ?
Save as simply takes a file path, typically you would do something like this.
fleUpload.SaveAs(Server.MapPath("~/Images/Uploadded/new.jpg"))
or similar, to get a physical file path for the save.
Once it is saved, you can do whatever you want with it.
NOTE: You want to consider security/validation that the user really provided an image etc when doing this.
SaveAs takes a local path (that is local to the web server) as a parameter.
You need to make sure the account that the site is running under has permissions to save to that location.
If you want to load an image from that path, you need to make sure it is mapped within the webserver and can be served from it (using a virtual directory, for example).
You can set the Image.ImageUrl with the virtual path.

Resources