【问题标题】:MVC 3 image upload pathMVC 3 图片上传路径
【发布时间】:2012-04-30 02:46:02
【问题描述】:

我正在尝试上传图片和缩略图。

我已经将web.config中的上传路径设置为<add key="UploadPath" value="/Images"/>

当我上传图片时,它会获取应用程序所在的硬盘驱动器和文件夹的完整路径|:

D:\Projects\Social\FooApp\FooApp.BackOffice\Images\image_n.jpg

但我只想要/images/image_n.jpg

我正在使用Path.Combine,你认为是这个原因吗?

我该如何解决这个问题?

这是代码|:\

foreach (var file in files)
                {
                    if (file != null && file.ContentLength > 0)
                    {
                        var fileName = Path.GetFileName(file.FileName);
                        if (fileName != null) originalFile = Server.MapPath(upload_path) + DateTime.Now.Ticks + "_ " + fileName;


                        file.SaveAs(originalFile); 

                        images.Add(originalFile);
                    }
                }

【问题讨论】:

标签: c# asp.net-mvc-3 image path


【解决方案1】:

我假设此代码在您的一个控制器中。 你试过了吗:

Server.MapPath(yourPath);

【讨论】:

    【解决方案2】:

    您需要使用HttpContext.Current.Server.MapPath

    返回与 Web 服务器上指定的虚拟路径相对应的物理文件路径。

    您的代码可能如下所示:

    Path.Combine(HttpContext.Current.Server.MapPath("~/Images"), fileName);
    

    *EDIT - 我正在添加您在上面提供的代码。它看起来像这样。

    foreach (var file in files)
    {
        if (file != null && file.ContentLength > 0)
        {
            var fileName = Path.GetFileName(file.FileName);
            var uploadPath = "~/Images"; //This is where you would grab from the Web.Config. Make sure to add the ~
    
            if (fileName != null) {
                var originalFile = Path.Combine(HttpContext.Current.Server.MapPath(uploadPath), DateTime.Now.Ticks + "_ " + fileName);
                file.SaveAs(originalFile); 
                images.Add(originalFile);
            }
        }
    }
    

    【讨论】:

    • Path.Combine 也适用于虚拟路径?我总是将它用于物理文件路径。
    猜你喜欢
    • 2011-08-27
    • 2018-01-01
    • 1970-01-01
    • 2017-07-27
    • 2019-02-06
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    相关资源
    最近更新 更多