英文:
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("Content-Disposition", "attachment; filename=Main.cs");
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("~/Main.cs"));
string fileName = "Main.cs";
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
Then, you can link to this action method from your download button:
<a href="@Url.Action("DownloadFile", "ControllerName")"><button type="button">Download</button></a>
Replace "ControllerName" with the name of the controller that contains the DownloadFile
action method.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论