2012-01-05 81 views
2

一個有圖片上傳功能適用於本地主機正常,但當我嘗試和Windows Server 2003下運行,我得到錯誤信息一般性錯誤+

這是代碼..

現在任何人在我面前跳;)我已經看了前面的答案,我已經檢查了所有的權限,他們似乎是正確的..文件夾/路徑存在,等等。

ImageService imageService = new ImageService(); 

if (fileBase != null && fileBase.ContentLength > 0 && fileBase.ContentLength <= 2097152 && fileBase.ContentType.Contains("image/")) 
{ 
    var uploadedPath = "~/Assets/Images/"; 

    Path.GetExtension(fileBase.ContentType); 
    var extension = Path.GetExtension(fileBase.FileName); 

    if (extension.ToLower() != ".jpg" && extension.ToLower() != ".gif") // only allow these types 
    { 
     photoViewModel.ImageValid = "Not Valid"; 
     ModelState.AddModelError("Photo", "Wrong Image Type"); 
     return View(photoViewModel); 
    } 

    EncoderParameters encodingParameters = new EncoderParameters(1); 
    encodingParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L); 

    ImageCodecInfo jpgEncoder = imageService.GetEncoderInfo("image/jpeg"); 
    var uploadedimage = Image.FromStream(fileBase.InputStream, true, true); 

    Bitmap originalImage = new Bitmap(uploadedimage); 
    Bitmap newImage = new Bitmap(originalImage, 274, 354); 

    Graphics g = Graphics.FromImage(newImage); 
    g.InterpolationMode = InterpolationMode.HighQualityBilinear; 
    g.DrawImage(originalImage, 0, 0, newImage.Width, newImage.Height); 

    var streamLarge = new MemoryStream(); 
    newImage.Save(streamLarge, jpgEncoder, encodingParameters); 

    var fileExtension = Path.GetExtension(extension); 
    string newname; 
    if (photoViewModel.photoURL != null) 
    { newname = photoViewModel.photoURL; } 
    else 
    { newname = Guid.NewGuid() + fileExtension; } 

    var ImageName = newname; 
    newImage.Save(Server.MapPath(uploadedPath) + ImageName); 
    System.IO.File.WriteAllBytes(Server.MapPath(uploadedPath) + ImageName, streamLarge.ToArray()); 

    photoViewModel.uploadedPath = uploadedPath; 
    photoViewModel.photoURL = ImageName; 

    originalImage.Dispose(); 
    newImage.Dispose(); 
    streamLarge.Dispose(); 
    return View(photoViewModel); 
} 
+1

我知道你說不要跳,但只是爲了排除不良的權限的可能性,你可以試着寫一個測試文件(任何內容)在同一個位置。 – 2012-01-05 10:40:32

+0

如果您收到錯誤消息,請添加您收到的消息 – Reniuz 2012-01-05 10:45:14

+0

@Reniuz:GDI中發生了一般性錯誤+ – beebul 2012-01-05 10:47:35

回答

3

隨着Image.FromStream中,流必須在圖像的整個生命週期內保持打開狀態。這意味着如果流是一個文件,文件將保持打開狀態。我認爲您需要處理uploadedImage以允許關閉流(如果您等待GC清理uploadedImage,這將在未來發生的不確定時刻發生 - 或根本不會發生)。

+0

那麼GC.Collect();幫幫我? – beebul 2012-01-05 10:54:35

+2

我不會推薦它(它使用大錘來破解堅果)。只需在不需要時處理它。 – 2012-01-05 23:27:49

+0

謝謝你幫助乾杯賈森! – beebul 2012-01-06 10:03:43