How to work with FileUpload in a WebPage? - asp.net-2.0

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.

Related

FileUpload control in asp.net throwing exception

I am trying to read an Excel sheet using C# which is to be loaded by end user from fileUpload control.
I am writing my code to save the file on server in event handler of another button control(Upload). But when I click on Upload Button I am getting this exception:
The process cannot access the file 'E:\MyProjectName\App_Data\sampledata.xlsx' because it is being used by another process.
Here is the code that I have used in event handler:
string fileName = Path.GetFileName(file_upload.PostedFile.FileName);
string fileExtension = Path.GetExtension(file_upload.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
//if (File.Exists(fileLocation))
// File.Delete(fileLocation);
file_upload.SaveAs(fileLocation);
Even deleting the file is not working, throwing the same exception.
Make sure, some other process is not accessing that file.
This error might occurs whenever you are trying to upload file, without explicitly removing it from memory.
So try this:
try
{
string fileName = Path.GetFileName(file_upload.PostedFile.FileName);
string fileExtension = Path.GetExtension(file_upload.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
//if (File.Exists(fileLocation))
// File.Delete(fileLocation);
file_upload.SaveAs(fileLocation);
}
catch (Exception ex)
{
throw ex.Message;
}
finally
{
file_upload.PostedFile.InputStream.Flush();
file_upload.PostedFile.InputStream.Close();
file_upload.FileContent.Dispose();
//Release File from Memory after uploading
}
The references are hanging in memory, If you are using Visual Studio try with Clean Solution and Rebuild again, if you are in IIS, just do a recycle of your application.
To avoid this problems try to dispose the files once you used them, something like:
using(var file= new FileInfo(path))
{
//use the file
//it will be automatically disposed after use
}
If i have understood the scenario properly.
For Upload control, I don't think you have to write code for Upload Button. When you click on your button,your upload control has locked the file and using it so it is already used by one process. Code written for button will be another process.
Prior to this, check whether your file is not opened anywhere and pending for edit.

ASP.NET Photo Upload

When uploading a photo to my server using the following code, I'm receiving an erroneous value. This is working fine in the debug mode and when published in localhost.
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"), date);
if (!Directory.Exists(HttpContext.Server.MapPath("../Uploads")))
{
Directory.CreateDirectory(HttpContext.Server.MapPath("../Uploads"));
}
file.SaveAs(filePath);
Can someone please point out what I've done incorrectly?
ok I am assuming that you are using File Upload control or you can use the below sample code if you want to use the FileUpload control in your asp.net page.
Add the FileUpload control (Here im adding ajax async FileUpload control and named as asyncFileUpload.
Write A Method and Call it whenever you want.
public int AsyncFileUpload()
{
string xlsFile = AsyncFileUpload1.FileName;
if (AsyncFileUpload1.HasFile)
{
string FileName = Path.GetFileName(AsyncFileUpload1.PostedFile.FileName);
string Extension = Path.GetExtension(AsyncFileUpload1.PostedFile.FileName);
string FilePath = Server.MapPath("~/Uploads/" + FileName);
if (Extension == ".doc")//check the file extension here
{
AsyncFileUpload1.SaveAs(FilePath);
}
}
}

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

Displaying image using Image control in button click event

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).

What's the best way to show a random image in ASP.NET?

What I am talking about is like this website :
http://www.ernesthemingwaycollection.com
It has a static wallpaper and a set of images that change from page to page, I want to implement a similar way of displaying random images from a set of images using ASP.NET.
EDIT : I want the image to stay the same in a session, and change from a session to another.
The site you mentioned is not using a random set of images. They are coded into the html side of the aspx page.
You could place an asp Image control on your page. Then on the page's Page_Load function set the image to a random picture of your set.
protected void Page_Load(object sender, EventArgs e)
{
this.Image1.ImageUrl = "~/images/random3.jpg";
}
You have different options on where to store the image set data. You could use a database and store the urls in a table. This would allow to use the built-in Random function found in SQL. Or you can save a XML file to the server, load that then use the Random .Net class to pick one of your xml nodes.
Personally i would recommend the Database solution.
EDIT: Because the server session is destroyed after 20mins you may want to look at using cookies so you can see the last random image they saw.
If you just want to rotate a set number of images you could use the ASP.NET AdRotator control (at last, a use for it!).
If you want to do something fancier, considering using a jQuery slideshow such jQuery Cycle Plugin. There is also a slideshow control in the AjaxControlToolkit, which is easy to integrate.
string imageDir = "/images/banner/";
public static string chooseImage(string imageDir)
{
string[] dirs = Directory.GetFiles(HttpContext.Current.Server.MapPath("~/images/" + imageDir + "/"), "*.*");
Random RandString = new Random();
string fileFullPath = dirs[RandString.Next(0, dirs.Length)];
// Do not show Thumbs.db ---
string fileName = string.Empty;
do
{
fileName = System.IO.Path.GetFileName(fileFullPath);
} while (fileName.Contains(".db"));
string imgPath = "/images/" + imageDir + "/" + fileName;
return imgPath;
}
private int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}

Resources