【问题标题】:Image upload in folder mvc 5 C#在文件夹 mvc 5 C# 中上传图像
【发布时间】:2016-08-25 16:14:05
【问题描述】:

当我尝试上传图像并将其保存在服务器的某个文件夹中时,file.SaveAs(path) 行中出现错误System.UnauthorizedAccessException

查看:

控制器:

 public ActionResult LoadImage()
    {


        return View();
    }

    public ActionResult Upload(HttpPostedFileBase file)
    {
        //String path = Server.MapPath("~/img/" + file.FileName);
        if (file != null)
        {

            String pic = System.IO.Path.GetFileName(file.FileName);
            String path = System.IO.Path.Combine(Server.MapPath("~"), pic);
            file.SaveAs(path);
        }

        return RedirectToAction("index", "Home", null);

【问题讨论】:

    标签: image file-upload directory asp.net-mvc-5


    【解决方案1】:

    UnauthorizedAccessException 意味着:

    • 调用者没有文件夹所需的权限。
    • 该文件是一个正在使用的可执行文件。
    • 路径指定了一个只读文件。

    More Info on

    解决方法:使用服务器文件夹而不是完整路径

    在解决方案(或任何您的选择)中创建一个图像文件夹作为图像的存储空间..

        [HttpPost]
        public ActionResult Upload(HttpPostedFileBase file)
        {
            if (file != null)
            {
                //Get the file name 
                var pic = System.IO.Path.GetFileName(file.FileName);
                //Get the folder in the server
                var imagesDir = System.Web.HttpContext.Current.Server.MapPath("~/image/");
                var imgPath = imagesDir + pic;
                file.SaveAs((imgPath));
            }
            return RedirectToAction("index", "Home", null);
        }
    

    干杯,

    【讨论】:

      【解决方案2】:

      此异常的可能原因有:

      • 您上传图像的文件夹未授予权限。 (如果没有给出,则提供对该文件夹的读写权限)
      • 您上传的文件夹是只读的。
      • 该文件是一个可执行文件,可能正在使用中。

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 2014-05-02
        • 1970-01-01
        • 1970-01-01
        • 2020-03-23
        • 1970-01-01
        • 1970-01-01
        • 2015-11-28
        • 2018-09-04
        • 1970-01-01
        相关资源
        最近更新 更多