【问题标题】:Is it possible to save uploaded files in ~/Content? (ASP.NET MVC2)是否可以将上传的文件保存在 ~/Content 中? (ASP.NET MVC2)
【发布时间】:2011-05-26 13:29:24
【问题描述】:

在调试/测试时,我一直在尝试将传入的上传图像保存在我的开发机器上的 ~/Content 中,但那里没有传输任何文件。该文件夹是否允许将图像保存/传输到它,还是我需要将它们保存在 ~/App_Data 中?


编辑:我正在使用的代码:

public ActionResult(AdminGameEditModel formData)
{
    Game game = new Game();

    AutoMapper.Mapper.Map<AdminGameEditModel, Game>(formData, game);

    if (formData.BoxArt.ContentLength > 0 && formData.IndexImage.ContentLength > 0)
    {
        var BoxArtName = Path.GetFileName(formData.BoxArt.FileName);
        var BoxArtPath = Path.Combine(Server.MapPath("~/Content/Images/BoxArt"), BoxArtName);
        game.BoxArtPath = BoxArtPath;
        formData.BoxArt.SaveAs(BoxArtPath);

        var IndexImageName = Path.GetFileName(formData.IndexImage.FileName);
        var IndexImagePath = Path.Combine(Server.MapPath("~/Content/Images/GameIndexImages"), IndexImageName);
        game.IndexImagePath = IndexImagePath;
        formData.IndexImage.SaveAs(IndexImagePath);
    }

    // rest of controller method
}

两个文件都是HttpPostedFileBase 对象。我目前使用的服务器只是在VS调试期间运行的ASP.NET服务器。

【问题讨论】:

    标签: c# asp.net-mvc-2 file-upload appdata


    【解决方案1】:

    您可以在磁盘上的任意位置复制/保存图像和文件。
    您只需检查 IIS 进程是否有权访问该文件夹。
    我倾向于创建一个自定义文件夹来放置我上传的文件。

    【讨论】:

      【解决方案2】:

      您应该能够将上传的文件保存到您选择的任何目录。关键是确保运行 ASP.NET 的服务帐户具有对该文件夹的写入权限。对于 IIS 7 或更高版本,它可能是服务器上的网络服务帐户。可以肯定的是,请查看您的网站在 IIS 中运行的应用程序池,并检查其运行的身份。


      更新:

      我明白了。您可以试试这个,看看该类型的 SaveAs 方法是否存在问题(我记得有些人对此有问题)。

      代替:

      formData.BoxArt.SaveAs(BoxArtPath);
      

      尝试:

      using (var output = new FileStream(BoxArtPath, FileMode.CreateNew)) {
        var data = new byte[formData.BoxArt.ContentLength];
        formData.BoxArt.InputStream.Read(data, 0, data.Length);
        output.Write(data, 0, data.Length);
      }
      

      【讨论】:

      • 如果我现在没有在 IIS 上运行怎么办?正在使用 VS 2010 调试器进行测试。该网站尚未实际部署。
      • 您使用什么代码获取上传的文件并将其保存到该文件夹​​?
      • 尝试更改这些行。 var BoxArtName = Path.GetFileName(formData.BoxArt);到 var BoxArtName = Path.GetFileName(formData.BoxArt.FileName);
      • HttpPostedFileBase 对象有一个 FileName 属性及其文件名。我很惊讶在 HttpPostedFileBase 类型上使用的 Path.GetFileName 没有出现异常。
      • 其实我也有。抱歉,远离开发机器并试图从内存中写入。我的代码基于我从 Phil Haack 的教程中读到的内容:haacked.com/archive/2010/07/16/…
      猜你喜欢
      • 2013-09-13
      • 1970-01-01
      • 2010-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多