What is the best way to delete an image in MVC?

I created an MVC application where you can upload images. I store them in the file system, and if the file exists, I display it and I do not use SQL to track the files.

I have an IList string with a foreach metric. but now I need to delete a specific image, and I'm not sure how to implement it in MVC, because I can only identify the image with imagename.

Can someone show me the best way to manage photos in my script. Thank you in advance

+4
source share
4 answers

You asked for an example, so we go. Imagine you want to delete an image saved in "/pics/path/mypic.jpg". You must call first

string path = Server.MapPath("/pics/path/mypic.jpg"); 

to get the physical path of the image and save it in a variable path. Then you can do:

 FileInfo fi = new FileInfo(path); if(fi.Exists) fi.Delete(); else what you want to do if file does'nt exists. 

Note: fi.Delete () does not throw an exception if the file does not exist.

To get a list of all the files in a directory, you can use Directory.GetFiles () or an instance of DirectoryInfo.

+4
source

You want to take a look at System.Web.HttpServerUtility.MapPath. You can give it a virtual image path (/images/picture.jpg) and it will return you the absolute path (C: \ web \ mysite \ images \ picture.jpg). Now you can delete the image.

+1
source

Not sure to understand the problem, MVC or something else: it doesn't matter. An image is a file on the server, so you can delete it just like any other file, for example, using Server.Mappath to allow FileInfo and play Delete on it.

0
source

Now Iโ€™m quite sure how to interpret your question ... MVC seems completely out of context.

But ... As I can see, you have a controller named ImageController with the "Delete" action. The action takes a FormCollection parameter, which when called contains the name of the image.

So, when you delete, you have a form that does a POST in ImageController-> Delete Action and passes the name of the image with it. The image name is contained in a hidden field.

As a note: using a name as an identifier may not be such a good idea. One reason is a reverse access attack. Ex providing "... / .. / .. /" instead of the image name. If you are not good at white listing / confirming your entries, this type of attack is likely to be possible.

http://en.wikipedia.org/wiki/Directory_traversal

0
source

All Articles