MVC文件上传UnauthorizedAccessException

时间:2012-11-02 13:03:16

标签: c# asp.net-mvc-3 visual-studio-2010

我有这段代码:

[HttpPost]
    public ActionResult Edit(Photograph photo, HttpPostedFileBase image)
    {

        if (ModelState.IsValid)
        {
            if (image != null)
            {
                byte[] imageData = new byte[image.ContentLength];
                image.InputStream.Read(imageData, 0, image.ContentLength);
                System.IO.File.WriteAllBytes(HttpContext.Server.MapPath("~/Content/Images"), imageData);
            }

            repository.SavePhotograph(photo);
            TempData["message"] = string.Format("{0} has been saved", photo.Name);
            return RedirectToAction("Index");
        }
        else
        {
            return View(photo);
        }
    }

用于从表单上传照片并将其保存在服务器(本地服务器)中。我给了“Visual Studio 2010”文件夹,其中所有项目都保留了NETWORK SERVICE用户权限和IIS_IUSRS组权限。我也是以管理员身份运行visual studio。

出于某种原因,它仍然不允许我将文件保存到该位置。该位置位于{Project_Name \ Content \ Images}下的项目文件夹中。如何将文件保存到那里?

谢谢,

3 个答案:

答案 0 :(得分:1)

它给我这个错误的原因是因为方法:

System.IO.File.WriteAllBytes()

采取,FILE和数据的路径。

我正在传递一个文件夹

System.IO.File.WriteAllBytes(HttpContext.Server.MapPath("~/Content/Images"), imageData);

我应该传递一个文件:

System.IO.File.WriteAllBytes(String.Format("{0}{1}", HttpContext.Server.MapPath("~/Content/Images"), image.FileName), imageData);

现在我的存储库出现错误,所以我正在调查:)我喜欢这么多编码......;)

答案 1 :(得分:0)

  

出于某种原因,它仍然不允许我将文件保存到该位置。

你有任何错误吗?如果是,请在此处发布完整错误。

案例I:如果您使用Visual Studio运行MVC应用程序,请确保使用“以管理员身份运行”选项运行visual studio。

案例II:如果您在IIS上运行MVC应用程序。转到保存图像的文件夹。这是授予'IIS_IUSRS'用户完全控制'修改'权利。

答案 2 :(得分:0)

RE:带有“System.IO.File.WriteAllBytes”的行...你想保存到目录吗?它在哪里为上传的文件选择了文件名?