File A replaced on server with B but File A is displayed - c#

I've run into a problem in a situation where an image is deleted and another file with the same name is saved in its stead (i.e. the file is replaced). As shown below:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult _ReplaceGeneral(int ID, HttpPostedFileBase file)
{
var dbpath = query.FindImages(ID);
var path = Server.MapPath(dbpath.ImageURL);
System.IO.File.Delete(path);
file.SaveAs(path);
TempData["Message"] = "Image Successfully Replaced!";
return RedirectToAction("EditGallery");
}
In my server the file is successfully replaced. However, when I launch the site, the previous image is displayed.
Notes:
The Image isn't saved in my database- it's saved on my Server and the URL is stored on the database.
I can physically see the file replaced in the server so I'm absolutely positive it's being replaced.
Question: How and why does Image A display on my website even after replacing it with Image B?
I haven't been able to find any resources that articulate why and how this issue occurs so I apologize if it's a duplicate.

This sounds like a browser caching issue. If the URL of the image does not change the browser will use the cached version and not fetch the image from the server.
You can get round this by getting the image files last modified date/time convert that to a number and add it to the image URL as a query string (e.g. &t=XXXXX). In this way when the image file changes the URL changes too. The browser will then load the new image.

Related

unable to load a local resource OR virtual path error

Situation
I have two applications that both read and save images / documents to one specific folder. Example if the user uploads their image in one program, a user of program B is supposed to view and even edit that image.
What I have done
In one of my application I have created a setting in settings for the string of my path. So to save an image path I call
path = System.IO.Path.Combine(Properties.Settings.Default.imagePath, Fimage);
this works fine.
However, my issue is when I try to view the image in my edit view.
Controller
ViewBag.imagePath = Properties.Settings.Default.imagePath;
View
<img src="#ViewBag.imagePath/#Url.Content(#Model.image)" alt="Image" style="height: 255px; " />
Problem
The problem is upon attempting to view the image I get the error, Not allowed to load local resource: I have full access to the folder and when I attempt to browse to the file in the error message the picture is displayed. I was advised from other questions to use, server.MapPath however when I do Server.MapPath(Properties.Settings.Default.imagePath); I get the error physical path received, expected virtual path.
This viewbag holds the entire string of folder my files are stored with the EVERYONE user having full access. So i'm really unsure of why it's making a fuse.
P.S I cant say something like "~/content/images" because the path to that file is in an entirely different application, I think I need to give it the entire location.
Any assistance will be appreciated.
Gratitude
Looks like your defaultImage variable holds a physical path, which will work for saving the image since the API requires a path in the form e.g. c:\website\images\.... but for viewing, you need the VirtualPath, something of the form http://mycoolsite/images/image.jpg and this is what the error is telling you.
Your Controller; therefore, should return something like
ViewBag.imagePath = Properties.Settings.Default.imagePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty);
In order to get the Relative Path. See this other related question.
EDIT I just saw your "PS..."
If that's the case, then you need to pass the full URL to the other application: (e.g. http://someothersite.com/images/image.jpg).

Saving images from IP Camera to folder in application

I have a camera connected to a network that provides images which can be accessed by IP. For example something like this.
http://170.1.2.3/image?camera=2
I get returned a jpg file, which I can easily display back on a webpage using normal html.
<img src="http://170.1.2.3/image?camera=2" />
But instead of simply showing the camera image as seen from the time of the page load, I also want to save this image locally to the server using an MVC4 application. In addition it would be nice to include a timestamp on the filename. I'm not having any luck finding an example that looks right to me.
Let's say I want to start with the most basic example:
string imgUrl = "http://170.1.2.3/image?camera=2";
savelocally(imgurl, "newfilename-"+DateTime.Now.ToString());
.. and savelocally() should place the file in "~/Uploads". How do I do this? All the examples I've come across have been for uploading a file from desktop. I don't know how to translate that into grabbing a remote image.
Update:
This is an incomplete answer, as pointed out by comments.
string url = "http://170.1.2.3/image?camera=2";
string localFilename = #"C:\Projects\MvcApplication1\MvcApplication1\Uploads\tofile.jpg";
using (WebClient client = new WebClient())
{
client.DownloadFile(url, localFilename);
}
It works, however I don't like the fact that the file path is an absolute one. I tried replacing localFilename with ~/Uploads/tofile.jpg but it results in an error on execution. If possible I want to avoid having a fixed location for the upload folder.

Creating Image object using System.Drawing.Image.FromFile

I am trying to get the image dimensions of an image that user selects from list box. Image files are available on FTP server. I am displaying file names in a list box for users to select. Upon selection, I want to show the preview of image, for that I want to get dimensions so that I can resize it if i need to.
I am storing file name that is linked to currently selected list item into a string variable. I know that path on the server. I am using following code to create the Image object, but having no luck
try
{
string dir = Session["currentUser"].ToString();
System.Drawing.Image img = System.Drawing.Image.FromFile("~/Uploads/"+dir+"/"+fName, true); //ERROR here, it gives me file URL as error message!
}
catch(Exception ex)
{
lbl_Err.Text = ex.Message;
}
Not sure what is going wrong. Any ideas?
use Server.MapPath to fetch the image from the server.
As follows
System.Drawing.Image img =
System.Drawing.Image.FromFile(Server.MapPath("Uploads/"+dir+"/"+fName), true);
You can use following as well
Server.MapPath(".") returns the current physical directory of the file (e.g. aspx) being executed
Server.MapPath("..") returns the parent directory
Server.MapPath("~") returns the physical path to the root of the application
Server.MapPath("/") returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)
References
Server.MapPath("."), Server.MapPath("~"), Server.MapPath(#"\"), Server.MapPath("/"). What is the difference?

C# - Get Image path from Client Machine

I want to get the path of the Image which is saved in Client Machine. I know the Path and the file name of the Image. By using FileUpload i can do it, but without using fileupload is it possible to get the path of the file ??.
My Scenario is given below,
Public void ConverttoByte()
{
//Get the image path from web.config & this image is in client machine
string strConfig = #"C:\Manikandan\image\image1.jpg";
MemoryStream MS = new MemoryStream();
Byte[] data;
int fiFileSize;
System.Drawing.Image image;
image = System.Drawing.Image.FromFile(strConfig);
image.Save(MS, System.Drawing.Imaging.ImageFormat.Gif);
data = MS.ToArray();
CallDBMethod(data);
}
Here I converted the image as Byte and I called the CallDBMethod to insert this byte details to DB..
This image is available in client machine, but not in server machine..
So, how to i get this image path from client machine & how can i solve this?
Without the File upload control, It is not possible unless you create an Activex control (may not work in all browsers. User has to give permission to run this control).
In a web application, You can not take ( steal) any file from the user's computer without them making an action to do so( ex : selecting the file in the File Input control and clicking some upload button).
If you want the full file path of the file user selected in the file upload control, you can get by HttpPostedFile.FileName property which gives you the fully qualified name of the file on the client (Ex : C:\MySomeFolder\SomeFile.jpg).
string fullPath=FileUpload1.HttpPostedFile.FileName
Assuming FileUpload1 is the ID of the File Upload control.
According to my knowledge it is not possible. You can't get the client's image path. The browser does not allow us to get the path. Using fileupload control you can also not get the complete path.
A similar question by me
How to Get complete file path using file upload control in asp.net or any other way?

how to download file from webserver when url contains only file ID

We have video clip storage and we want to provide url link to the end user for the clips so that end user can start downloading the clips by clicking on the url. But trick here is url link is not direct path to the clip file stored on the virtual folder but url contains clip ID. It might look like,
www.xyz.com/clipstore/ID
When end user click on the url, server should search for the clip in the clip storage, process the clip ( convert from one format to other format) and start download at end user location.
Can anyone please guide us how server can initiate download for the end user when url is not directly pointing to the file but ID of it.
We are using IIS 6 / 7 , C# on the server side. Client is silverlight based.
It is possible and quite straight forward in ASP.net MVC.
For the sake of example, I have hard coded the mime type to "image/png", but i should be according to file type.
public ActionResult clipstore(string id)
{
var path = GetFilePathByID(id);
StreamReader reader = new StreamReader(path);
var fileBytes = System.IO.File.ReadAllBytes(path);
FileContentResult file = File(fileBytes, "image/png");
return file;
}

Categories