如何在不知道其扩展名的情况下获取文件-ASP.NET MVC [英] How to get a file without knowing its extension - ASP.NET MVC

查看:50
本文介绍了如何在不知道其扩展名的情况下获取文件-ASP.NET MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

服务器中的文件夹"Images"中有一个文件.

There is a file in folder "Images" in server.

该文件的名称为"jason",但我不知道它是"jason.pdf"还是"jason.jpg"或"jason.png".但是,该文件必须具有以下扩展名之一:".pdf,.png,.jpg".没有其他选择.

The file's name is "jason", but I don't know if it is "jason.pdf" or "jason.jpg" or "jason.png".. However the file must have one of these extensions : ".pdf, .png, .jpg". There is no other option.

我知道如果我知道它的扩展名是".pdf",就可以得到这样的文件:

I know I can get the file like this if I know its extension is ".pdf" :

<a href="~/Images/jason.pdf">File</a>

但是,如果我不知道它的扩展名,我不知道该怎么办.如何在不知道其扩展名但仅知道文件名的情况下获取文件?预先感谢.

But I don't know what to do if I don't know its extension. How can I get the file without knowing its extension but knowing only file name? Thanks in advance.

推荐答案

您可以考虑创建为您提供这些文件的控制器操作.

You may consider creating an controller action which serves you these files.

这里是一个快速简单的示例.随时对其进行编辑以使其更加精致和美观.根据需要强大.

Here is a quick-working-simple example. Feel free to edit it to make it ophisticated & robust as needed.

public class ImageController:Controller
{
    private string GetFilePath(string fileName)
    {
        var path = Server.MapPath(Url.Content("~/Images"));
        //Getting all the files present in this directory
        var files = Directory.GetFiles(path);

        // Loop through each items(filenames) and  check the filename(without extension)
        // is matching with our method parameter value
        foreach(var file in files)
        {
            if(Path.GetFileNameWithoutExtension(file)
                   .Equals(fileName,StringComparison.OrdinalIgnoreCase))
            {
                return file;
            }
        }
        return string.Empty;
    }
    [Route("image/{fileName}")]
    public ActionResult GetFile(string fileName)
    {
        var path = GetFilePath(fileName);
        // to do : handle if path is string.empty
        // may be return default content/file ?
        var contentType = MimeMapping.GetMimeMapping(path);
        byte[] bytes = System.IO.File.ReadAllBytes(path);
        return File(bytes, contentType);
    }
}

现在在其他视图中,您将其称为

Now in your other view, you will call this as

<a href="~/Image/jason">PDF File</a>

 <a href="~/Image/puppy">Image file name</a>

在这里,我们为方法使用属性路由,以便将对/image/{filename}的请求映射到GetFile方法.通过在RouteConfig.csRegisterRoutes方法中调用MapMvcAttributeRoutes方法来确保启用了属性路由.

Here we are using attribute routing for our method so that the request to /image/{filename} will be mapped to the GetFile method. Make sure you have attribute routing enabled by calling MapMvcAttributeRoutes method inside RegisterRoutes method of RouteConfig.cs.

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");                    
        routes.MapMvcAttributeRoutes();

        //Existing default route defnition goes here           
    }
}

没什么要考虑的

  1. 上面的简单实现是每次调用action方法时都读取Images目录中的所有文件.您应该考虑缓存结果(文件名列表,返回值GetFiles),以便避免一直进行调用.您可以将其存储在内存缓存/数据库等中.

  1. The above simple implementation is reading all the files in the Images directory every time the action method is invoked. You should consider caching the results(list of file names, return value of GetFiles) so that you can avoid making the call all the time. You can store it in an in memory cache/ database etc.

如果用户传递的文件名在该位置不存在,那么您要返回什么.在这种情况下,上面的GetFilePath方法将返回string.empty.在GetFile方法中处理它.

If user is passing a file name which does not exist in the location, what do you want to return. The GetFilePath method above returns string.empty in that case. Handle it inside the GetFile method.

这篇关于如何在不知道其扩展名的情况下获取文件-ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆