【问题标题】:How do I store an uploaded file to a location other than the application folder in MVC application如何将上传的文件存储到 MVC 应用程序中的应用程序文件夹以外的位置
【发布时间】:2014-04-03 00:16:30
【问题描述】:

我可以使用此代码成功上传文件:

 [HttpPost]
    public ActionResult Save(IEnumerable<HttpPostedFileBase> attachments)
    {
        // The Name of the Upload component is "attachments" 
        foreach (var file in attachments)
        {
            // Some browsers send file names with full path. This needs to be stripped.
            var fileName = Path.GetFileName(file.FileName);
            var physicalPath = Path.Combine(Server.MapPath("~/App_Data"), fileName);
            file.SaveAs(physicalPath);
        }
        // Return an empty string to signify success
        return Content("");
    }

但这会将文件放在正在运行的应用程序 App_Data 文件夹中。我想将文件放在我的局域网上的共享中。我已经尝试过下面的代码,但它总是将 myPath 附加到应用程序的路径中:

 [HttpPost]
public ActionResult Save(IEnumerable<HttpPostedFileBase> attachments)
    {
        // The Name of the Upload component is "attachments" 
        foreach (var file in attachments)
        {

// Some browsers send file names with full path. This needs to be stripped.
            var fileName = Path.GetFileName(file.FileName);
            //add possible new folder name to path
            var myPath = "//my-server-myshare/myfolder/";
            //combine with file name 
            var physicalPath = Path.Combine(Server.MapPath(myPath), fileName);

            file.SaveAs(physicalPath);
        }
        // Return an empty string to signify success
        return Content("");
    }

如何强制将其保存在我作为 myPath 的 URL 中?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 file-upload


    【解决方案1】:

    网络共享需要是完整的 UNC 路径,因此请翻转斜线:

    var myPath = @"\\my-server-myshare\myfolder\";
    

    你也可以直接创建文件:

    file.Create(@"\\my-server-myshare\myfolder\");
    

    【讨论】:

    • 我尝试了您的第一个解决方案,但出现“无法识别的转义序列错误。
    • @X3074861XI 如果我使用这样的映射驱动器号,则能够使其工作: myPath = @"I\MyFolder\";我真的更愿意使用我询问的路径,但我想这现在可行。
    • 我对第一行进行了编辑,它只需要字符串文字指定 (@)。
    猜你喜欢
    • 2015-01-03
    • 2020-12-17
    • 1970-01-01
    • 2015-05-09
    • 2014-08-27
    • 2016-05-27
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    相关资源
    最近更新 更多