public ActionResult _Upload(HttpPostedFileBase file, GaleriesViewModel galeriesViewModel)
{
Images image = new Images();
if (file.ContentLength > 0)
{
try
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/Galeries/Galery_" + galeriesViewModel.sno), fileName);
var smallImagePath = Path.Combine(Server.MapPath("~/Images/Galeries/Small/Galery_" + galeriesViewModel.sno), fileName);
var db_file_url = "Images/Galeries/Galery_" + galeriesViewModel.sno + "/" + fileName;
var db_small_image_url = "Images/Galeries/Small/Galery_" + galeriesViewModel.sno + "/" + fileName;
//exception thrown in this line
file.SaveAs(path);
Image smallImage = Image.FromFile(path);
Size size = new Size();
size.Height = 128;
size.Width = 128;
smallImage = ImageManager.ResizeImage(smallImage, size);
smallImage.Save(smallImagePath);
smallImage.Dispose();
image.ContentType = file.ContentType;
image.CreatedOn = DateTime.Now;
//image.CreateUserId = WebSecurity.CurrentUserId;
image.GaleryId = galeriesViewModel.sno;
image.ImageUrl = db_file_url;
image.Name = fileName;
image.UploadSize = file.ContentLength;
image.SmallImageUrl = db_small_image_url;
entity.Images.Add(image);
entity.SaveChanges();
}
catch (Exception ex) { }
}
galeriesViewModel.Galeries = entity.Galeries;
ViewData["Selected"] = galeriesViewModel.sno;
return View("ImageOperations", galeriesViewModel);
}
我可以使用此代码上传图片。但是,当我尝试连续添加相同的图像时,我再次收到写为标题的错误。我怎样才能解决这个问题?这是什么原因?
更新
图像管理器类
public static class ImageManager
{
public static Image ResizeImage(Image imgToResize, Size size)
{
int sourceWidth = imgToResize.Width;
int sourceHeight = imgToResize.Height;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)size.Width / (float)sourceWidth);
nPercentH = ((float)size.Height / (float)sourceHeight);
if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap b = new Bitmap(destWidth, destHeight);
Graphics g = Graphics.FromImage((Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
g.Dispose();
return (Image)b;
}
}
谢谢