简体   繁体   English

Path.GetFullPath —仅返回最后一个文件夹,文件名和扩展名

[英]Path.GetFullPath — Return only the last folder, file name and extension

I am trying to get the path for files within the web app, but it returns the path within my computer. 我正在尝试获取Web应用程序中文件的路径,但它返回了我计算机中的路径。

I am using mvc 5 and ef 6, basically users can upload pictures, all uploaded pictures goes into ~/Upload_Files/"username of current user"/ 我正在使用mvc 5和ef 6,基本上用户可以上传图片,所有上传的图片都放入〜/ Upload_Files /“当前用户的用户名” /

The upload method will get the username of the current user and if if that folder exist, if not it creates one and upload all pics into that folder. upload方法将获取当前用户的用户名,如果该文件夹存在,则创建一个并将所有图片上传到该文件夹​​。

The main action method is to display all pictures within /Upload_Files folder included the ones inside sub folders. 主要的操作方法是显示/ Upload_Files文件夹中的所有图片,包括子文件夹中的图片。

This is within that action method: 这是在该操作方法内:

var imagesModel = new ImageGallery();
var imageFiles = Directory.GetFiles(
    Server.MapPath("~/Upload_Files/"), "*.*", SearchOption.AllDirectories);

foreach (var item in imageFiles)
{
    // imagesModel.ImageList.Add(Path.GetFileName(item));
    imagesModel.ImageList.Add(Path.GetFullPath(item));
}
return View(imagesModel);`

Inside cshtml to display the pictures 在cshtml内部显示图片

<img src="@Url.Content(image)" width="150" height="150"/>

If I use GetFullPath, it will return the location within my computer so pictures wont show. 如果我使用GetFullPath,它将返回计算机中的位置,因此不会显示图片。

I tried it with GetFileName and create the rest of the string as ("~/Upload_Files" + item) which would work if the pictures are stored only within Upload_Files folder and not in sub folders. 我用GetFileName进行了尝试,并以(“〜/ Upload_Files” + item)创建字符串的其余部分,如果图片仅存储在Upload_Files文件夹中而不是子文件夹中,则可以正常工作。 Also tried user ("~/Upload_Files/" + User.Identity etc + "/" + item) and so on. 也尝试过用户(“〜/ Upload_Files /” + User.Identity等+“ /” +项目),依此类推。 Anyone could give me an idea on this please? 有人可以给我一个想法吗? Just started mvc recently. 最近刚开始mvc。

Also my main goals are to display all images within sub folders, if user click on picture it will pull up all pictures only for that user (which is just to reference his/her username somehow) and lastly to allow users to delete their own pictures. 我的主要目标也是显示子文件夹中的所有图像,如果用户单击图片,它将仅拉出该用户的所有图片(只是以某种方式引用其用户名),最后允许用户删除自己的图片。 Any more convenient way of doing it? 还有其他更方便的方法吗?

Any help much appreciated! 任何帮助,不胜感激!

New Method 新方法

Upload Image Method 上传图片方法

if (Request.Files.Count != 0)
        {
            for (int i = 0; i < Request.Files.Count; i++)
            {
                HttpPostedFileBase file = Request.Files[i];
                int fileSize = file.ContentLength;
                string fileName = file.FileName;
                string user = User.Identity.GetUserName();
                string path = Server.MapPath("~/Upload_Files/" + user + "/");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                file.SaveAs(Server.MapPath("~/Upload_Files/" + user + "/" + fileName));
                ImageGallery imageGallery = new ImageGallery();
                imageGallery.ID = Guid.NewGuid();
                imageGallery.Name = fileName;
                imageGallery.ImagePath = "~/Upload_Files/" + user + fileName;
                imageGallery.UserId = user;
                db.ImageGallery.Add(imageGallery);
                db.SaveChanges();
            }
            return Content("Success");
        }
        return Content("failed");

Index action method 索引动作方法

public ActionResult Indexnew()
    {
        var imagesModel = new ImageGallery
        {
            ImagePath = Datalayer.GetImagePaths()
        };
        return View("Indexnew", imagesModel);
    }

ImageGallery class ImageGallery类

public class ImageGallery
{
    public ImageGallery()
    {
        ImageList = new List<string>();
    }
    [Key]
    public Guid ID { get; set; }
    public string UserId { get; set; }
    public string Name { get; set; }
    public IEnumerable<string> ImagePath { get; set; }
    public List<string> ImageList { get; set; }

}

Indexnew View 索引新视图

@model MM5.Models.ImageGallery
@foreach (var image in Model)
            {
                <p>@image</p>
                <a id="ShowImage" title="Photo" href="@Url.Action("Details","ImageGallery", User.Identity.Name)">

                    @*<img src="@Url.Content("~/Upload_Files/" + image. + "/" + image)" width="150" height="150" />*@
                    <img src="@Url.Content(image)" width="150" height="150" />

                </a>
            }

I think my view is completely wrong. 我认为我的观点是完全错误的。

If you need to map images which are in target directory or it's sub-directories, then I would suggest this: 如果您需要映射目标目录或其子目录中的图像,则建议这样做:

public string ReverseMapPath(string path)
{
    string appPath = Server.MapPath("~");
    return string.Format("~{0}", path.Replace(appPath, "").Replace("\\", "/"));
}

...

imagesModel.ImageList.Add(ReverseMapPath(item));

Basically, the ReverseMapPath function translates given file system path into application virtual path. 基本上, ReverseMapPath函数ReverseMapPath给定的文件系统路径转换为应用程序虚拟路径。 For example: 例如:

D:\\Web\\MyApp\\Upload_Files\\User123\\Holiday\\Italy.jpg

is translated into 被翻译成

~/Upload_Files/User123/Holiday/Italy.jpg

Just wondering why such function does not already exist inside framework. 只是想知道为什么这样的功能在框架内还不存在。

I would suggest not calling methods from inside your view. 我建议不要从您的观点内部调用方法。 You can get path mapping however by using 您可以使用以下方法获取路径映射

var path = Server.MapPath("~/Upload_Files");

You should pass a ViewModel to your view with all of the paths of your images 您应该将ViewModel和所有图像路径传递给视图

You should have a relative mapping, or have setup a virtual directory hosted on IIS, and then take the relative paths and append them. 您应该有一个相对映射,或者已经建立了一个托管在IIS上的虚拟目录,然后采用相对路径并附加了它们。 You should store your image directory in your 您应该将图像目录存储在

Web.config

<add key="ImageUrl" value="/Upload_Files/" />

Controller

    public ActionResult Index()
    {
        var homeVm = new HomeVM
        {
            ImagePaths = DataLayer.GetImagePaths()
        };
        return View("Index", homeVm);
    }

ViewModel

    class HomeVM
    {
            public IEnumerable<string> ImagePaths { get; set; }
    }

DataLayer

I would suggest not enumerating the files each time as this will severely hinder performance of your application. 我建议不要每次都枚举文件,因为这会严重影响应用程序的性能。 You should store the urls of the images in a database and perform something like 您应该将图像的URL存储在数据库中并执行类似的操作

    public static IEnumerable<string> GetImagePaths()
    {
        var imageUrl = ConfigurationManager.AppSettings["ImageUrl"];
        var db = new MyDataClassDataContext();
        var value = (from im in db.Images select imageUrl + im.Path).ToList();
        db.Dispose();
        return value;
    }

So, whenever an image is uploaded or changed, you should modify the value in your table. 因此,无论何时上传或更改图像,都应修改表中的值。 This will greatly increase performance of your application 这将大大提高应用程序的性能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM