how to avoid image getting loaded from the cache - c#

I am using asp.net file upload control
I am uploading the image to the server as as UserID+"ProfilePic" .
After uploading I am setting an image src to this via code behind
string FolderPath = System.Configuration.ConfigurationManager.AppSettings["PATH"].ToString();
string assoid = HttpContext.Current.Session["strAssociateId"].ToString()+"ProfilePic.jpg";
if (FileUpload1.HasFile)
{
try
{
string fileName = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(FolderPath +assoid);
string imagePath = "serverpath" +assoid;
face_crop_original.Src = imagePath; //Problem is here
}
}
So here what happens is the image is getting uploaded, but when I set the image.Src=xxxx it's taking the old image from cache!! Please help.

public static string VersionCssUrl(string url)
{
// Get physical path.
try
{
var path = HttpContext.Current.Server.MapPath(url);
return url + "?v=" + String.Format(File.GetLastWriteTime(path).ToString("MMddyyhhmmss"));
}
catch
{
return url;
}
}
and your code will look like this
<img src="<%= VersionCssUrl("your src".ToString()) %>" />
Now,Explaination you know what will happen is this will request the file everytime but it will check modification date of your file so you will have previous one if does not changed will definately load from cache.....
and if your file has been changed it will load new file automatically this all depends on your datetime.....
i hope this will help you regards...:)

I found a simple solution which is working for me :)
You can check the source here
What I did is I attached the datetime.now as #dholakiyaankit suggested but in a different place
string fileName = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(FolderPath +assoid);
string imagePath = "server path" +assoid;
face_crop_original.Src = imagePath+"?"+DateTime.Now;
NOTE: Here my imagepath variable will be "xxxxxx.jpg" so
face_crop_original.Src = imagePath+"?"+DateTime.Now;
will be "http://xxxxxxxx.com/imagename.jpg?Randomnumber"
This enabled me to upload the image with same name (USERID+"Profilepic") and i need not write code for deleting older file as the name will be same and it will be replaced in server !

Related

Store locally a binary file file received as HTTP POST body [duplicate]

I want upload an image file to project's folder but I have an error in my catch:
Could not find a part of the path 'C:\project\uploads\logotipos\11111\'.
What am I do wrong? I want save that image uploaded by my client in that folder... that folder exists... ah if I put a breakpoint for folder_exists3 that shows me a true value!
My code is:
try
{
var fileName = dados.cod_cliente;
bool folder_exists = Directory.Exists(Server.MapPath("~/uploads"));
if(!folder_exists)
Directory.CreateDirectory(Server.MapPath("~/uploads"));
bool folder_exists2 = Directory.Exists(Server.MapPath("~/uploads/logo"));
if(!folder_exists2)
Directory.CreateDirectory(Server.MapPath("~/uploads/logo"));
bool folder_exists3 = Directory.Exists(Server.MapPath("~/uploads/logo/" + fileName));
if(!folder_exists3)
Directory.CreateDirectory(Server.MapPath("~/uploads/logo/"+fileName));
file.SaveAs(Server.MapPath("~/uploads/logo/" + fileName+"/"));
}
catch(Exception e)
{
}
Someone knows what I'm do wrong?
Thank you :)
Try this:
string targetFolder = HttpContext.Current.Server.MapPath("~/uploads/logo");
string targetPath = Path.Combine(targetFolder, yourFileName);
file.SaveAs(targetPath);
Your error is the following:
bool folder_exists3 = Directory.Exists(Server.MapPath("~/uploads/logo/" + fileName));
if(!folder_exists3)
Directory.CreateDirectory(Server.MapPath("~/uploads/logo/"+fileName));
You check if a directory exists, but you should check if the file exists:
File.Exists(....);
You need filename
file.SaveAs(Server.MapPath("~/uploads/logo/" + fileName+"/" + your_image_fillename));
Remove the last part of the path to save you have an extra "/"
It should be
file.SaveAs(Server.MapPath("~/uploads/logo/" + fileName);
Also you do not have a file extension set.

Not getting the Uploaded filepath in asp.net

I want to save file to a specific location with some folder creation based on my requirement. So I wrote the below code.
public string CreateFilePath(string addedFolderName)
{
string folderPath = ConfigurationManager.AppSettings["DocDirectory"].ToString();
string FileUplPath = folderPath + "\\" + addedFolderName + "\\";
if (!Directory.Exists(FileUplPath))
{
Directory.CreateDirectory(FileUplPath);
}
flUploadDocs.SaveAs(FileUplPath + Path.GetFileName(flUploadDocs.FileName));
return folderPath;
}
But I am unable to get the filepath here. I am getting it as null
getting null at
Path.GetFileName(flUploadDocs.FileName)
<asp:FileUpload ID="flUploadDocs" runat="server" />
Please suggest what is wrong here.
Path.GetFileName() returns the file name and extension of the specified path string
if im correct this only fills in the file name and not the directory + name.
Path.GetFileName(flUploadDocs.FileName)
possible solution
Path.GetFileName(FileUplPath+flUploadDocs.FileName)
eventough im confused why you try to retrieve the path again after just having saved it?
The issue is that the webservice does not have the fileupload data. Here is the full code from our extended conversation:
[WebMethod]
public static string InsertUpdateMWSiteData(MWInsertUpdateFields MWInsertUpdateFields)
{
string strInsertUpdateMWInfo = "";
try
{
Dashboard dshb = new Dashboard();
dshb.CreateFilePath(MWInsertUpdateFields.SapID + "_" + MWInsertUpdateFields.CandidateID);
strInsertUpdateMWInfo = CommonDB.InsertUpdateMWSiteInfo(MWInsertUpdateFields);
}
catch (Exception)
{
throw;
}
return strInsertUpdateMWInfo;
}
public string CreateFilePath(string addedFolderName)
{
string folderPath = ConfigurationManager.AppSettings["DocDirectory"].ToString();
string FileUplPath = folderPath + "\\" + addedFolderName + "\\";
if (!Directory.Exists(FileUplPath))
{
Directory.CreateDirectory(FileUplPath);
}
if (flUploadDoc.HasFile == true)
{
string strFilename = Path.GetFileName(flUploadDoc.FileName);
flUploadDoc.SaveAs(FileUplPath + Path.GetFileName(flUploadDoc.PostedFile.FileName));
}
return folderPath;
}
The problem is that after uploading a file, a request is sent to a webmethod which is being hosted in another instance of the program. This Webmethod checks its own instance for the fileupload control and data, and doesn't find it because it is in a different instance. This is why your fileupload control is returning null even on a sanity check of .HasFile().
One solution is to pass the data to the Webservice. You could for example pass the data to your webmethod as a byte[], and then on the webservice side reconvert it back into its original file type. After completing this process, save the file to your local filesystem. To do this you may need to pass the extension type and file name.
You may also want to add some validation to limit the file types accepted to only the most common file types like images, .doc, .excel, and whatever you have the library to support the conversion of.
If you want to save files directly to your filesystem using the upload control, you can do so but you will have to exclude the webservice step.
Please also see the discussion in chat for details.

Path is not a valid virtual path while uploading image to server in asp.net mvc

I want to upload image to the server, but image can be uploaded locally to a project folder with ~/images/profile, but if I use full path, it does not upload to the server. The code which I am using is given below with a sample url. Please help to solve my problem. I have seen other links of stackoverflow, but they are not working. It gives error message of path is not a valid. Virtual path and the SaveAs method is configured to require a rooted path, and the path is not rooted.
public ActionResult FileUpload(HttpPostedFileBase file, tbl_Image model)
{
if (file != null)
{
string pic = System.IO.Path.GetFileName(file.FileName);
string path = System.IO.Path.Combine(Server.MapPath("http://sampleApp.com/images/profile/"), pic);
file.SaveAs(path);
db.AddTotbl_Image(new tbl_Image() { imagepath = "http://sampleApp.com/images/profile/" + pic });
db.SaveChanges();
}
return View("FileUploaded", db.tbl_Image.ToList());
}
Why do you use site name ("http://sampleApp.com") in your code? I think you don't need that on saving.
public ActionResult FileUpload(HttpPostedFileBase file, tbl_Image model)
{
if (file != null)
{
string fileName = System.IO.Path.GetFileName(file.FileName);
string fullPath = System.IO.Path.Combine(Server.MapPath("~/images/profile"), fileName);
file.SaveAs(fullPath);
db.AddTotbl_Image(new tbl_Image() { imagepath = "http://sampleApp.com/images/profile/" + fileName });
db.SaveChanges();
}
return View("FileUploaded", db.tbl_Image.ToList());
}
You also can save only fileName in db for general goal. Because in future URL can change. (By domain name, SSL etc.)
Server.MapPath should not contain an url. That's for sure.
Also, don't use
string pic = System.IO.Path.GetFileName(file.FileName);
but just
string pic = file.FileName;

how to display image created dynamically in asp.net 3.5 c# on localhost

I have to display image dynamically. I have written code for that, i got the name of the image & path also from database i.e Filename & filepath which i stored earlier, but I didnt get image(not displaying image even i stored path of that image). Please give me idea about how to set imageurl of image here on local host. My code is as follow:
//PlaceHolder for adding images i.e inside formview control
PlaceHolder PHFilename = (PlaceHolder)FVViewCustData.FindControl("PHFilename");
for (int i = 0; i < dsfile.Tables[0].Rows.Count; i++)
{
HyperLink hypname = new HyperLink();
hypname.Text = Convert.ToString(dsfile.Tables[0].Rows[i]["FileName"]);
PHFilename.Controls.Add(hypname);
Image img = new Image();
//IPAddress is my ipaddress
img.ImageUrl = "IPAddress" + Convert.ToString(
dsfile.Tables[0].Rows[i]["FilePath"]);
PHFilename.Controls.Add(img);
}
If you keep the Image data in DB you can use image handler and load dynamically.
But if you keep the image URL in DB depends on what do you save filename or relative path or absolute path.
C# Save and Load Image from Database
There are couple of ways to solve your issues:
First Way:
Store all your images under some base directory - you can have sub-directories under it. The image path that you store in the database will be relative to this base directory. Now map this base directory as some virtual directory in your web site. Now you can use code such as
string imageVirtualDir = "/StoredImages/";
img.ImageUrl = imageVirtualDir + Convert.ToString(
dsfile.Tables[0].Rows[i]["FilePath"]);
Needless to say, base directory path and image virtual directory path will be configurable values.
Second Way:
You can store images wherever you wish. Let's say you get the complete physical path from the database. So you will set the image url such as
img.ImageUrl = "/ImageServer.ashx?path=" + Convert.ToString(
dsfile.Tables[0].Rows[i]["FilePath"]);
Here, you will need a simple http handler (ImageServer.ashx) to serve your images - the code will be something like
public class ImageServer : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var path = context.Request["path"];
context.Response.ContentType = "image/jpeg";
context.Response.TransmitFile(path);
}
public bool IsReusable
{
get
{
return false;
}
}
}
Note that this is just a template code to get you started. For production code, you need to have error handling, setting correct content type as per image type. Also, its not advisable to have physical image path in query string - so you need to pass either relative path or some token instead - for example, you can pass the row id so that your handler can query database and get the image path etc.

A problem with Relative Path Resolution when setting an Image Source

I have built a small WPF application that allows users to upload documents and then select one to display.
The following is the code for the file copy.
public static void MoveFile( string directory, string subdirectory)
{
var open = new OpenFileDialog {Multiselect = false, Filter = "AllFiles|*.*"};
var newLocation = CreateNewDirectory( directory, subdirectory, open.FileName);
if ((bool) open.ShowDialog())
CopyFile(open.FileName, newLocation);
else
"You must select a file to upload".Show();
}
private static void CopyFile( string oldPath, string newPath)
{
if(!File.Exists(newPath))
File.Copy(oldPath, newPath);
else
string.Format("The file {0} already exists in the current directory.", Path.GetFileName(newPath)).Show();
}
The file is copied without incident. However, when the user tries to select a file they just copied to display, A file not found exception. After debugging, I've found that the UriSource for the dynamic image is resolving the relative path 'Files{selected file}' to the directory that was just browsed by the file select in the above code instead of the Application directory as it seems like it should.
This problem only occurs when a newly copied file is selected. If you restart the application and select the new file it works fine.
Here's the code that dynamically sets the Image source:
//Cover = XAML Image
Cover.Source(string.Format(#"Files\{0}\{1}", item.ItemID, item.CoverImage), "carton.ico");
...
public static void Source( this Image image, string filePath, string alternateFilePath)
{
try
{image.Source = GetSource(filePath);}
catch(Exception)
{image.Source = GetSource(alternateFilePath);}
}
private static BitmapImage GetSource(string filePath)
{
var source = new BitmapImage();
source.BeginInit();
source.UriSource = new Uri( filePath, UriKind.Relative);
//Without this option, the image never finishes loading if you change the source dynamically.
source.CacheOption = BitmapCacheOption.OnLoad;
source.EndInit();
return source;
}
I'm stumped. Any thought's would be appreciated.
Although I don't have a direct answer, you should use caution for such allowing people to upload files. I was at a seminar where they had good vs bad hackers to simulate real life exploits. One was such that files were allowed to be uploaded. They uploaded malicious asp.net files and called the files directly as they new where the images were ultimately presented to the users, and were able to eventually take over a system. You may want to verify somehow what TYPES of files are being allowed and maybe have stored in a non-exeucting directory of your web server.
It turns out I was missing an option in the constructor of my openfiledialogue. The dialogue was changing the current directory which was causing the relative paths to resolve incorrectly.
If you replace the open file with the following:
var open = new OpenFileDialog{ Multiselect = true, Filter = "AllFiles|*.*", RestoreDirectory = true};
The issue is resolved.

Categories