2012-07-26 26 views
0

我有一個上傳圖片的代碼片段。上傳時,它暫時將該文件存儲在會話中。然後點擊「保存」,它將文件保存在數據庫中。爲什麼顯示「無法訪問關閉的文件」錯誤?爲什麼只在服務器上?

我的機器上沒有問題,但是在服務器上,每當我嘗試上載某些文件,然後單擊「保存」時,它就會顯示錯誤信息「無法訪問已關閉的文件」。在谷歌搜索它,我讀了here,這是由於大文件上傳。我想確認,是我上傳大文件的問題?或者它可能是別的東西? 另外,爲什麼我沒有得到這個在我的機器上,只有在服務器上?

編輯:順便說一下,錯誤出現了,當file size > 80kb

守則上傳文件:關於儲蓄

public ActionResult StoreLogoInSession(HttpPostedFileBase file, int assetID) 
     { 
      string filename = null; 
      if (ValidateOnUpload(file)) 
      { 
       Session.Add("TempLogo", file); 
       filename = file.FileName; 
       Session.Add("filename", filename); 
      } 
      return RedirectToAction("Edit", new { id = assetID }); 
     } 

代碼(這是發生錯誤時):

public ActionResult SaveLogo(LogoModel m, int assetID) 
     { 
       HttpPostedFileBase file = (HttpPostedFileBase)Session["TempLogo"]; 
       var logoModel = new LogoModel(); 
       var asset = this.GenerateAssetForUploadFile(file, (int)m.Asset.AccountID, m.Asset.TextContents, m.Asset.AssetName); 
       this.LogoManagementFacade.SaveLogo(asset); 
       logoModel.Asset = asset; 
       this.LogoModelList.Add(logoModel); 
} 
+1

使用會話不好。使用Session來存儲上傳的文件是一種令人憎惡的行爲。請不要。 – 2012-07-26 11:11:17

+0

好的,但是我現在面臨的這個問題呢? – 2012-07-26 11:14:02

+1

您面臨的問題是設計問題。不要爲此任務使用Session。我的意思是你正在使用錯誤的工具進行這項工作,現在你在問爲什麼它不起作用。不知道該告訴你什麼。祝你好運,這個問題。我無法幫助。我可以給你的最好建議是儘快擺脫這個Session。 – 2012-07-26 11:14:31

回答

0

解決此問題的第一件事是擺脫會話並臨時將上載的文件存儲在文件系統上,或者如果您正在共享的Web場中運行d文件夾,或者如果文件不夠大,甚至可以將它們存儲在數據庫中。

因此,讓我們假設您目前沒有在網絡農場中運行,並且您有一個Web服務器,並且我們可以將上傳的文件存儲在一個臨時文件夾中(當然,您會編寫一個可以運行的預定腳本每天晚上和刪除早於X天的文件,以避免浪費白白磁盤空間):

public const string AssetsFolderBase = "~/App_Data"; 

public ActionResult StoreLogo(HttpPostedFileBase file, int assetID) 
{ 
    string filename = null; 
    if (ValidateOnUpload(file)) 
    { 
     var folder = Path.Combine(Server.MapPath(AssetsFolderBase), assetID.ToString()); 
     if (!Directory.Exists(folder)) 
     { 
      Directory.CreateDirectory(folder); 
     } 
     folder = Path.Combine(folder, Path.GetFileName(file.FileName)); 
     file.SaveAs(folder); 
    } 
    return RedirectToAction("Edit", new { id = assetID }); 
} 

,然後當你需要訪問它:

public ActionResult SaveLogo(LogoModel m, int assetID) 
{ 
    var folder = Path.Combine(Server.MapPath(AssetsFolderBase), assetID.ToString()); 
    var file = Directory.GetFiles(folder).FirstOrDefault(); 
    if (file == null) 
    { 
     // no file with this assetID was uploaded => throw an exception 
     // or return 404 or something 
     return HttpNotFound(); 
    } 

    // at this stage the file variable is pointing to the uploaded filename 
    // => you could process it here ... 
} 

現在,如果你要處理大文件上傳你顯然應該確保adjust the proper settings in your web.config。默認情況下,您僅限於4MB。

哦,當你在編輯你的web.config確保您添加以下行,以確保沒有其他開發人員犯同樣的錯誤,你和不期而遇使用ASP.NET會話:

<sessionState mode="Off" /> 
相關問題