从ASP.net MVC项目下载文件的ActionLink和方法 [英] ActionLink and method to download file from ASP.net MVC project
问题描述
我在Visual Studio中有一个Asp.net核心MVC项目.我已经在项目中添加了一个名为Download的文件夹,并将文件"ReadMe.txt"添加到了该文件夹中.我正在尝试使用户能够下载文件.我认为我有:
I have an Asp.net core MVC project in visual studio. I have added a folder called Download to the project and added the file "ReadMe.txt" into that folder. I'm trying to enable the user to download the file. In my view I have:
@Html.ActionLink("Readme.txt", "ReadMe", "Download")
这将调用DownloadController中的ReadMe操作.但是,过去一个小时,我一直在努力编写action方法来返回文件.
This calls the ReadMe action inside the DownloadController. However, I have been struggling for the past hour to write the action method to return the file.
我认为应该执行类似的操作,但IDE无法识别服务器,并且无法找到导入来解决该问题.我已经尝试过使用System.Web,但无法正常工作.
I think something like this should do it but the IDE does not recognise Server and I cannot find an import to resolve it. I've tried using System.Web and it does not work.
public FileResult ReadMe()
{
string filename = "ReadMe_2.1.txt";
string serverpath = Server.MapPath("~/Download/");
string filepath = serverpath + filename;
return File(filepath, System.Net.Mime.MediaTypeNames.Application.Octet, filename);
}
有什么建议吗?
推荐答案
感谢Stephen Muecke指导我解决这个类似的问题: 使用MVC Core下载文件
Thanks to Stephen Muecke for directing me to this similar problem: Download File using MVC Core
在我自己努力寻找答案的同时,我还在这里提供了解决我的问题的代码,希望它可以在类似情况下帮助任何其他人:
As I struggled to find the answer myself, I also provide the code here that solved my issue in hope that it may help anybody else in similar circumstances:
public FileResult ReadMe()
{
var fileName = $"ReadMe_2.1.txt";
var filepath = $"Download/{fileName}";
byte[] fileBytes = System.IO.File.ReadAllBytes(filepath);
return File(fileBytes, "application/txt", fileName);
}
全部归功于 https://stackoverflow.com/users/5528313/vague
这篇关于从ASP.net MVC项目下载文件的ActionLink和方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!