首页 > 解决方案 > 如何使用 mvc 或 javascript 通过另存为对话框下载文件

问题描述

在我的项目中,我提供了下载文件的选项。所有文件都存在于服务器上的文件夹中。我已经使用锚标签做到了这一点

<a class="nav-link" href="/images/myfile.jpg" download >Download</a>

它默认将文件下载到下载文件夹中,但我想另存为对话框以询问下载/保存文件的位置。

在 C# 中我已经尝试过这个。以下代码还下载下载文件夹中的文件

public ActionResult index()
{
  Response.ContentType = "image/jpeg";
  Response.AppendHeader("Content-Disposition", "attachment; filename=121.jpg");
  Response.TransmitFile(Server.MapPath("~/images/121.jpg"));
  Response.End();

 return View();
}

标签: javascriptjqueryasp.net-mvc

解决方案


您可以直接返回文件,而不是使用return View()using return File()

public ActionResult index()
{
    string path = Server.MapPath("~/images/121.jpg");
    string contentType = "image/jpeg";

    return File(path, contentType, "121.jpg");
}

请注意,保存对话框窗口取决于客户端的浏览器设置,您无法从服务器端控制它。如果客户端浏览器启用自动下载到指定文件夹,则文件将下载到给定文件夹名称。


推荐阅读