Search code examples
c#asp.netasp.net-mvc-3httppostedfilebase

HttpPostedFileBase.SaveAs working but no file uploaded and no exceptions


First, here is my code:

private Shoe ProcessForm(Shoe shoe, HttpPostedFileBase image)
{
    try
    {
        shoe.Slug = CMSHelper.SanitizeTitle(shoe.Name);
        shoe.LastModification = DateTime.Now;

        if ((image != null) && (image.ContentLength > 0))
        {
            string fileName = String.Concat(shoe.ShoeId, Path.GetExtension(image.FileName));
            shoe.Image = fileName;

            string filePath = Path.Combine(Server.MapPath(shoe.ImagePath), fileName);
            image.SaveAs(filePath);
        }
    }
    catch (Exception e)
    {
        throw e;
    }

    return shoe;
}

Locally, this code works fine. Directories' permissions are fine. And it has worked before randomly on other servers (I tested this code on 4 or 5 different servers while I was testing VPS providers).

But if I try to run it from my home computer, everything passes alright, there's a file name saved in the database but no file is uploaded. And no exceptions are given!!!

I've been trying to fix this for almost three days and so much useless hours, please help me... I just don't see what's wrong with this...


Solution

  • I finally did a workaround which is doing very fine. I even asked at my job and everyone said there was nothing wrong at all. So screw it here's what I did:

    Instead of calling .SaveAs() I made a method which is :

    public static void WriteFileFromStream(Stream stream, string toFile)
    {
        using (FileStream fileToSave = new FileStream(toFile, FileMode.Create))
        {
            stream.CopyTo(fileToSave);
        }
    }
    

    I call it like this:

    CMSHelper.WriteFileFromStream(image.InputStream, filePath);
    

    And that's it.