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);
}
我可以用此代碼上傳圖片。但是,當我試圖連續添加相同的圖像時,我又會得到寫作標題的錯誤。我怎樣才能解決這個問題?這是什麼原因?該進程無法訪問該文件,因爲它正在被另一個進程使用?
UPDATE
的ImageManager類
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;
}
}
感謝
看起來像ImageManager仍在使用您的圖像。 – Mariusz