Reputation: 5
I'm working on a blog site and I want a feature where authors could upload images to be included with the post. I had it working just fine, but it was keeping the original file names. I figured this could be a problem in the future, so I tried making a GUID to avoid conflicts. This is what I'm looking at in my controller right now:
if (ImageUploadHelper.IsWebFriendlyImage(image))
{
var ext = Path.GetExtension(image.FileName);
image.SaveAs(Path.Combine(Server.MapPath("~/Uploads/"), ext));
blogPost.MediaUrl = "/Uploads/" + Guid.NewGuid() + ext;
}
...the "ImageUploadHelper" being a helper method to handle files that are too big and/or not the correct format. Anyway, as it is right now, posts can be created and I can see in SSMS that the MediaUrl is being saved in what looks like the correct format, but the files are not actually uploading and thus not displaying. Previously, I had this:
if (ImageUploadHelper.IsWebFriendlyImage(image))
{
var fileName = Path.GetFileName(image.FileName);
image.SaveAs(Path.Combine(Server.MapPath("~/Uploads/"), fileName));
blogPost.MediaUrl = "/Uploads/" + fileName;
}
...and everything was working well, with the exception that there was a potential for filename conflicts. What am I missing?
Upvotes: 0
Views: 37
Reputation: 584
It looks like you are saving just extensions?
image.SaveAs(Path.Combine(Server.MapPath("~/Uploads/"), ext));
So, please use this instead:
var newFileName = Guid.NewGuid() + ext;
image.SaveAs(Path.Combine(Server.MapPath("~/Uploads/"), newFileName));
blogPost.MediaUrl = "/Uploads/" + newFileName;
Upvotes: 1