是否可以发送文件响应以下载和重定向用户?要遵循的步骤是什么?如果有人可以提供资源或概述的链接,我将不胜感激。 我的场景是用户发送请求下载文件操作方法,然后操作方法发送文件下载并重定向用户
我尝试了如下:
[HttpGet]
[Authorize]
public ActionResult DownloadFile()
{
var currentUserId = User.Identity.GetUserId();
var invoices = _context.Invoices
.Where(x => x.OwnerId == currentUserId).ToList();
var directory = HttpContext.Server.MapPath("~/Temp");
var timeStamp = DateTime.Now.ToString("yyyy_MM_dd_HH_mm");
var fileName = string.Concat("myfile", "_", timeStamp, ".xlsx");
var filePath = Path.Combine(directory, fileName);
FileService fs = new FileService();
var file = fs.GenerateExcelFile(filePath, invoices);
Response.ClearHeaders();
Response.Headers.Add("Content-Disposition", "attachment; filename=" + fileName);
var contentType ="application/excel";
return File(filePath ,contentType);
// HOW do I send download file and return to view ??
}
答案 0 :(得分:0)
在您的视图中添加此代码。它使用jQuery和web api返回带附件头的文件。超时功能旨在允许一些时间从服务器请求文件。
<a id="link" href="#">Click here to download</a>
<script type="text/javascript">
$('#link').click(function (e) {
e.preventDefault(); //prevent browser to follow link
setTimeout(function () { //Redirected to new page in 2 sec
window.location.href = 'http://localhost:2981/Home/NewPage'
}, 2000);
window.location.href = 'http://localhost:2981/api/files/get/';
});
</script>
我的案例中的web api是一种虚拟方法。标题是重要的部分。您希望提示用户下载文件而不是重定向到该文件。因此,我们需要添加附件标题。
public class FilesController : ApiController
{
[HttpGet]
public HttpResponseMessage Get()
{
string result = "this is the file content";
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent(result, System.Text.Encoding.UTF8, "text/plain");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
return response;
}
}