为文件夹[javascript]中的文件生成URL链接列表

generate a list of URL links for files in folder [javascript]

本文关键字:URL 链接 列表 文件 文件夹 javascript      更新时间:2023-09-26

我想为文件夹中的每个文件生成列表。例如,如果我在特定文件夹中有以下文件

  • 示例图片1.jpg
  • sample_picture2.jpg

我想生成如下的URL链接

  • [0]-src='http://localhost/path/sample_picture1.jpg'
  • [1] -src='http://localhost/path/sample_picture2.jpg'

目前我是这样创建的。

json方法在文件夹中查找文件

    public JsonResult filesinfolder()
    {
        string salesFTPPath = "folder_path";
        DirectoryInfo salesFTPDirectory = new DirectoryInfo(salesFTPPath);
        IEnumerable<string> files = salesFTPDirectory.GetFiles()
          .Where(f => f.Extension == ".xls" || f.Extension == ".xml" || f.Extension == ".jps" || f.Extension == ".jpg" || f.Extension == ".jpeg" || f.Extension == ".png")
          .OrderBy(f => f.Name)
          .Select(f => f.Name);
        return Json(files, JsonRequestBehavior.AllowGet);
    }

获取文件的脚本

$(document).ready(function () {
    $.ajax({
        type: 'GET',
        url: '@Url.Action("filesinfolder", "Home")',
        dataType: "json",
        success: function (data) { onSuccess(data); },
        error: function (xhr, status, err) {}
    });
});
var onSuccess = function (data) {
};

因此,我想将结果作为URL列表(用于文件夹中的文件)发送到onSuccess

由于ajax调用是在document.ready上执行的,因此似乎没有必要使用ajax,您可以通过将url集合传递到视图来简化这一过程。假设您使用视图模型,添加一个属性(例如IEnumerable<string> ImageUrls { get; set; })(或者您可以将集合分配给ViewBag属性)

在生成视图的GET方法中

// get the files
IEnumerable<string> files = salesFTPDirectory.GetFiles().Where(....
// build urls
model.ImageUrls = new List<string>();
foreach (string name in files)
{
  model.ImageUrls.Add(Url.Content("~/path") + "/" + name);
}
return View(model);

在视图

@foreach(string url in Model.ImageUrls)
{
  <img src="@url" height="100" width="100" />
}

假设您查询生成的文件名是sample_picture1.jpgsample_picture2.jpg,那么这将生成

<img src="/path/sample_picture1.jpg" ... />
<img src="/path/sample_picture2.jpg" ... />

如果您确实想使用ajax来实现这一点,那么在filesinfolder()方法中生成如上所述的url并返回它们,然后在success回调中

success: function (data) {
  $.each(data, function(index, item) {
    var img = $('<img>').attr('src', item);
    $(someElement).append(img);
  });
}

附带说明:有点令人困惑的是,你有string salesFTPPath = "folder_path";,但你想生成.../path/...而不是.../folder_path/...(我认为其中一个是打字错误),但无论如何,一旦你发布了你的应用程序,这就不起作用了。您需要使用Server.MapPath()来生成文件夹的正确路径。