HttpPostedFileBase.SaveAs工作但没有上传文件,没有例外

Tom*_* B. 5 c# asp.net httppostedfilebase asp.net-mvc-3

首先,这是我的代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

在本地,这段代码工作正常.目录的权限很好.并且它在其他服务器上随机工作(我在测试VPS提供程序时在4或5个不同的服务器上测试了此代码).

但是,如果我尝试从我的家用计算机运行它,一切都顺利通过,数据库中保存了一个文件名但没有上传文件.没有例外!!!

我一直试图解决这个问题差不多三天而且这么多无用的时间,请帮助我......我只是不明白这有什么问题......

小智 5

你的视图模型是什么?首先将 (Shoe shoes, HttpPostedFileBase image) 替换为 (FormCollection formCollection)。在其上放置一个断点以查看您正在获取所有提交的值。如果你这样做了,那么模型绑定就会出现问题,我们需要解决这个问题。

编辑

你能不能设置一个断点

image.SaveAs(filePath); 
Run Code Online (Sandbox Code Playgroud)

添加对 fileName 和 filePath 变量的监视。我认为服务器路径不是您期望的那样,或者您可能正在一起查找错误的文件夹。告诉我们这些变量的值是多少。还要确保当你过去时没有抛出异常image.SaveAs(filePath);


Tom*_* B. 5

我最终做了一个解决方法,效果非常好。我什至问过我的工作,每个人都说没有任何问题。所以搞砸了,这就是我所做的:

我没有调用 .SaveAs() 而是创建了一个方法:

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

我这样称呼它:

CMSHelper.WriteFileFromStream(image.InputStream, filePath);
Run Code Online (Sandbox Code Playgroud)

就是这样。