【问题标题】:How to Show and Download a file in MVC如何在 MVC 中显示和下载文件
【发布时间】:2023-03-09 10:35:01
【问题描述】:

我正在上传一个文件,然后使用 Web API 显示他们的列表。文件名应该是一个链接,以便单击它时应该下载文件或用户可以看到它。这是我的代码。

控制器

  public ActionResult CreateFiles(long? clientId, long? freelancerId)
        {
            string apiEventCommon = string.Format("api/client/{0}/Event/Common", UserSession.ClientId);
            EventCommon eventCommon = HttpHandler.Get<EventCommon>(apiEventCommon, UserSession.AccessToken);
            FileInfoModel createFiles = new FileInfoModel();
            createFiles.AllFiles = eventCommon.FileTypes;
            createFiles.ClientId = Convert.ToInt64(UserSession.ClientId);
            createFiles.FreelancerId = 9;//hardcoded 
            clientId = createFiles.ClientId;//temp
            freelancerId = 9;//temp
            if (clientId != null && freelancerId != null)
            {
                string api = string.Format("api/client/{0}/freelancer/{1}/files", clientId, freelancerId);
                var fileDetail = HttpHandler.Get<List<FilesDetails>>(api, UserSession.AccessToken);
                createFiles.ExistingFiles = fileDetail;
            }
            return View(createFiles);
        }

查看

  @foreach (var file in Model.ExistingFiles)
                    {
                        <tr>
                            <td>
                                @{
                                    var length = @file.FileName.Length - 1;
                                }
                                @(@file.FileName.Length > 10 ? @file.FileName.Substring(0, 10) + "..." : @file.FileName)
                            </td>
                            <td>@file.FileSize</td>
                            <td>@file.UploadDate.ToString("MM/dd/yyyy")</td>
                            <td>
                                @Html.HiddenFor(x => x.Id)
                                @Html.HiddenFor(x => x.ClientId)
                                @Html.HiddenFor(x => x.FreelancerId)

                                <a class="posDelete" href="javascript:void(0)">
                                    <span id="fileSpan" class="noti glyphicon glyphicon-remove-circle" style="color:#D3B06E" onclick="DeleteFile('@file.Id','@file.FreelancerId','@file.Filecategory','@file.FileName');"></span>
                                </a>
                            </td>
                        </tr>
                                    }

我正在将文件保存到我的项目目录,并将它们的路径保存在数据库中。那么我该如何实现呢?

【问题讨论】:

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


    【解决方案1】:

    您需要向文件添加一个 html 链接,就像您可以在页面中添加指向其他元素的链接一样。

    <a href='path_to_the_file_or_page'>link_description</a>
    

    该文件应该可以使用浏览器访问,因此链接不会损坏。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-17
      • 2017-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多