I have a code snippet which uploads an image. On uploading, it temporarily stores the file in a Session. Then on click of “Save”, it saves the file in a database.
There’s no problem on my machine, but on the server, whenever I try to upload some files, and then click on “Save”, it shows me an error “Closed file cannot be accessed”. On Googling it, I read here that this was due to large files being uploaded. I wanted to confirm, is the problem that I’m uploading large files?? Or could it be something else?
Also, why am I not getting this on my machine and only on the server??
EDIT: By the way, the error showed up when the file size > 80kb
Code on Uploading file:
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 });
}
Code on Saving (this is when the error occurs):
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);
}
The first thing into fixing this issue is to get rid of the Sessions and temporarily store the uploaded file on the file system or if you are running in a web farm on a shared folder or if the files are not large enough you could even store them in the database.
So let’s suppose that currently you are not running in a web farm and you have a single web server and that we could store the uploaded files in a temporary folder (for which of course you will write a scheduled script that could run every night and delete older than X days files to avoid wasting disk space for nothing):
and then when you need to access it:
Now if you want to handle large file uploads you should obviously make sure to adjust the proper settings in your web.config. By default you are limited to 4MB.
Oh and while you are editing your web.config make sure you add the following line to ensure that no other developers make the same mistake as you and accidentaly use the ASP.NET Session: