根据条件mvc asp从文件夹中获取文件

时间:2016-12-26 07:37:58

标签: c# asp.net-mvc file download

我有两个表,注意和文件(一对多)。 我将所有文件保存在“Files”文件夹中,然后除了NoteID(FK)之外,还保存了文件表中的名称,路径,扩展名。

我成功上传了它们。 但是当我想根据NoteID条件下载文件时,我不能。 我可以获取该文件夹中的所有文件。

我的问题是如何根据条件从特定文件夹中获取某些文件? 我尝试了几种解决方案,但它们不起作用。

任何帮助?

动作:

public ActionResult Download(int NoteID)
{

    var fs = db.Files.Where(f => f.NoteID == NoteID);

    string[] files = Directory.GetFiles(Server.MapPath("/Files"));


    for (int i = 0; i < files.Length; i++)
    {
        files[i] = Path.GetFileName(files[i]);
    }
    ViewBag.Files = files;
    return View();
}

public FileResult DownloadFile(string fileName)
{
    var filepath = System.IO.Path.Combine(Server.MapPath("/Files/"), fileName);
    return File(filepath, MimeMapping.GetMimeMapping(filepath), fileName);
}

下载视图:

@{
    ViewBag.Title = "Download Files";
    var Files = (ViewBag.Files as string[]);

    if (Files != null && Files.Any())
    {
        foreach (var file in Files)
        {
            <br />
            @Html.ActionLink(file, "DownloadFile", new { fileName = file })
            <br />

        }
    }
    else
    {
        <label>No File(s) to Download</label>
    }
}

编辑:

上面的代码正在运行并获取并显示“文件”文件夹中的所有文件

当我尝试运行下面的代码时,我得到IOEception

动作:

  public ActionResult Download(int? NoteID)
    {


        var fs = db.Files.Where(f => f.NoteID == NoteID);


        string[] files = new string[(fs.Count()) - 1];



        int counter = 0;

        foreach (var item in fs)
        {
            files[counter] = Directory.GetFiles(Server.MapPath("/Files/"+item.FileName)).Single();
            /*here is the Exception
             * 
            System.IO.IOException:
            { "The directory name is invalid.\r\n"}

            InnerException message:
            The directory name is invalid.    
            */

        }



        for (int i = 0; i < files.Length; i++)
        {
            files[i] = Path.GetFileName(files[i]);
        }
        ViewBag.Files = files;
        return View();
    }

    public FileResult DownloadFile(string fileName)
    {
        var filepath = System.IO.Path.Combine(Server.MapPath("/Files/"), fileName);
        return File(filepath, MimeMapping.GetMimeMapping(filepath), fileName);
    }

查看:

@{
    ViewBag.Title = "Download Files";
    var Files = (ViewBag.Files as string[]);

    if (Files != null && Files.Any())
    {
        foreach (var file in Files)
        {
            <br />
            @Html.ActionLink(file, "DownloadFile", new { fileName = file })
            <br />

        }
    }
    else
    {
        <label>No File(s) to Download</label>
    }
}

1 个答案:

答案 0 :(得分:2)

在新代码中:

 let Username:NSString = EmailTextField.text! as NSString
 let password:NSString = PasswordTextField.text! as NSString


 let headers = [
            "content-type": "application/json",
            "cache-control": "no-cache",
            "postman-token": "121b2f04-d2a4-72b7-a93f-98e3383f9fa0"
        ]
 let parameters = [
            "username": "\(Username)",
            "password": "\(password)"
        ]

 if let postData = (try? JSONSerialization.data(withJSONObject: parameters, options: [])) {

        var request = NSMutableURLRequest(url: URL(string: "YOUR_URL_HERE")!,
                                              cachePolicy: .useProtocolCachePolicy,
                                              timeoutInterval: 10.0)
        request.httpMethod = "POST"
        request.allHTTPHeaderFields = headers
        request.httpBody = postData

        let session = URLSession.shared

        let task = URLSession.shared.dataTask(with: request as URLRequest) {
               (data, response, error) -> Void in
                if (error != nil) {
                    print(error)
                } else {
                    DispatchQueue.main.async(execute: {

                      if let json = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? NSDictionary
                        {
                            let success = json["status"] as? Int
                            let message = json["message"] as? String
                            // here you check your success code.
                            if (success == 1)
                            {
                                print(message)
                                let vc = UIActivityViewController(activityItems: [image],  applicationActivities: [])
                                 present(vc, animated: true)
                            }
                            else
                            {

                               // print(message)
                            }

                        }

                    })
                }
            }

            task.resume()
        }

您使用的参数不正确。您正在传递文件路径,但此方法需要目录路径。

您可以使用:

files[counter] = Directory.GetFiles(Server.MapPath("/Files/"+item.FileName))

但在您的情况下,我认为最好使用Directory.EnumerateFiles方法。请阅读here

所以新代码将是:

var filteredByFilename = Directory
                        .GetFiles(Server.MapPath("/Files"))
                        .Select(f => Path.GetFileName(f))
                        .Where(f => f.StartsWith("yourFilename"));

ViewBag.Files = filteredByFilename.ToArray();

整个下载方法可以是:

var filteredByFilename = Directory
                        .EnumerateFiles(Server.MapPath("/Files"))
                        .Select(f => Path.GetFileName(f))
                        .Where(f => f.StartsWith("yourFilename"));

ViewBag.Files = filteredByFilename.ToArray();