需要帮助使HTML中的C#文件可以下载。

huangapple go评论70阅读模式
英文:

need help making it so that there is a download for a c# file in HTML

问题

我尝试使用户单击按钮时自动下载C#文件。这是我使用的代码:

<a href="Main.cs" download="test_image"><button type="button"> 下载 </button>

然而,每当用户单击下载按钮时,它只是显示文件中的代码。是否可能使用户自动下载文件?我找到的任何网站都没有解决这个问题。

英文:

I tried to make it so that when the user clicks a button they automatically download the c# file. This is the code I used:

<a href="Main.cs" download="test_image"><button type="button"> Download </button>

Whenever the user clicks the download button though, it just shows them the code from the file. Is it possible to make it so that the user automatically downloads the file. No website I have found helps with this problem.

答案1

得分: 1

你需要将文件的Content-Disposition头设置为"attachment"。在C#中,你可以在你的Main方法的开头添加以下一行代码:

Response.Headers.Add("Content-Disposition", "attachment; filename=Main.cs");

这将把"Content-Disposition"头设置为"attachment",并指定文件名为"Main.cs"。当用户点击下载按钮时,浏览器会提示他们保存文件,而不是显示它。

另外,如果你正在使用ASP.NET,你可以使用FileContentResult方法将文件返回为可下载的内容结果,像这样:

public ActionResult DownloadFile()
{
    byte[] fileBytes = System.IO.File.ReadAllBytes(Server.MapPath("~/Main.cs"));
    string fileName = "Main.cs";
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}

然后,你可以从下载按钮链接到这个操作方法:

<a href="@Url.Action("DownloadFile", "ControllerName")"><button type="button">Download</button></a>

将"ControllerName"替换为包含DownloadFile操作方法的控制器的名称。

英文:

You'll need to set the Content-Disposition header of the file to "attachment". To do this in C#, you can add the following line of code at the beginning of your Main method:

Response.Headers.Add(&quot;Content-Disposition&quot;, &quot;attachment; filename=Main.cs&quot;);

This will set the "Content-Disposition" header to "attachment" and specify the filename as "Main.cs". When the user clicks the download button, the browser will prompt them to save the file instead of displaying it.

Alternatively, if you're using ASP.NET, you can use the FileContentResult method to return the file as a downloadable content result, like this:

public ActionResult DownloadFile()
{
    byte[] fileBytes = System.IO.File.ReadAllBytes(Server.MapPath(&quot;~/Main.cs&quot;));
    string fileName = &quot;Main.cs&quot;;
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}

Then, you can link to this action method from your download button:

&lt;a href=&quot;@Url.Action(&quot;DownloadFile&quot;, &quot;ControllerName&quot;)&quot;&gt;&lt;button type=&quot;button&quot;&gt;Download&lt;/button&gt;&lt;/a&gt;

Replace "ControllerName" with the name of the controller that contains the DownloadFile action method.

huangapple
  • 本文由 发表于 2023年5月11日 01:26:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76221132.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定