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

时间:2011-10-05 03:41:22

标签: c# asp.net asp.net-mvc-3 httppostedfilebase

首先,这是我的代码:

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;
}

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

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

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

7 个答案:

答案 0 :(得分:4)

您的视图模型是什么?首先用(FormCollection formCollection)替换(Shoe shoe,HttpPostedFileBase图像)。在其上设置一个断点,以确定您获得了所有提交的值。如果你这样做,那么模型绑定就会出现问题,我们需要解决这个问题。

修改

你能否在

上设一个断点
image.SaveAs(filePath); 

为fileName和filePath变量添加监视。我认为服务器路径不是您所期望的,或者您可能正在查找错误的文件夹。告诉我们这些变量的值是什么。还要确保在超过image.SaveAs(filePath);

时不会抛出任何异常

答案 1 :(得分:3)

我终于做了一个非常好的解决方法。我甚至问我的工作,每个人都说没有任何错误。所以把它搞砸了我的所作所为:

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

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

我称之为:

CMSHelper.WriteFileFromStream(image.InputStream, filePath);

就是这样。

答案 2 :(得分:2)

image.FileName包含路径数据,由

选择
Path.Combine(Server.MapPath(shoe.ImagePath), fileName)

尝试类似:

string pathForSaving = Server.MapPath("~/Upload/Images");
string uploadFileName = System.IO.Path.GetFileName(image.FileName);
string uploadFilePathAndName = Path.Combine(pathForSaving, uploadFileName);
image.SaveAs(uploadFilePathAndName);

答案 3 :(得分:0)

你是如何设置shoe.ImagePath的?您的问题感觉就像Server.MapPath返回的是您不期望的值。

答案 4 :(得分:0)

您是否检查过是否有多台网络服务器?或许像负载均衡器一样。它可能不会抛出异常,因为实际上没有异常并且文件确实存在于某个地方,而不是在您认为它所在的服务器上。只是一个想法(以前发生在我身上)。

答案 5 :(得分:0)

确保您在表单

中使用 enctype =“multipart / form-data”

http://www.prideparrot.com/blog/archive/2012/8/uploading_and_returning_files

答案 6 :(得分:0)

我也遇到了在这个帖子上发布的同一个问题,经过几次上传文件的尝试后,我刷新了文件所在的文件夹,最后我在那里看到了它们。不确定为什么它在第一次刷新后没有第一次显示,但它可能与刷新文件夹有关。我在Visual Studio中进行了刷新,并且还有“显示所有文件”按钮。