Reputation: 588
I have an asp.net mvc app where I am able to upload multiple images at once and that works fine, but I have an issue with creating thumbnail images out of the originals.
Here's the code:
[HttpPost]
public ActionResult SaveUploadedFile()
{
bool isSavedSuccessfully = true;
string fName = "";
try
{
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
fName = file.FileName;
if (file != null && file.ContentLength > 0)
{
var originalDirectory = new DirectoryInfo(string.Format("{0}Images", Server.MapPath(@"\")));
string pathString = Path.Combine(originalDirectory.ToString(), "Gallery");
string pathString2 = Path.Combine(originalDirectory.ToString(), "Gallery\\Thumbs");
//var fileName1 = Path.GetFileName(file.FileName);
bool exists = Directory.Exists(pathString);
bool exists2 = Directory.Exists(pathString2);
if (!exists)
Directory.CreateDirectory(pathString);
if (!exists2)
Directory.CreateDirectory(pathString2);
var path = string.Format("{0}\\{1}", pathString, file.FileName);
file.SaveAs(path);
//WebImage img = new WebImage(file.InputStream);
WebImage img = new WebImage(fileName);
//if (img.Width > 1000)
img.Resize(100, 100);
img.Save(pathString2);
}
}
}
catch (Exception ex)
{
isSavedSuccessfully = false;
}
if (isSavedSuccessfully)
{
return Json(new { Message = fName });
}
else
{
return Json(new { Message = "Error in saving file" });
}
}
So basically file.SaveAs(path);
is the last line that works and I actually save the images, but after that line I try to create and save thumbs but it does not work (I do get the Thumbs
folder created before though).
I also get the Error in saving file
response but that is because I am trying to create and save the thumbs, if I remove that then I don't get it, and I do not know how to return the actual error to actually see what the error is.
Upvotes: 3
Views: 2983
Reputation: 588
The answer is this:
var path2 = string.Format("{0}\\{1}", pathString2, file.FileName)
WebImage img = new WebImage(file.InputStream);
img.Resize(250, 250);
img.Save(path2);
Upvotes: 2