Nav*_*eth 4 c# asp.net downloadfile asp.net-core
在Aspnet5 RC1 update1 Web应用程序中,尝试与Response.BinaryWrite一样,在旧的AspNet应用程序中下载文件.用户需要在客户端获得弹出保存对话框.
使用以下代码时,客户端会出现一个弹出提示以保存文件.
public void Configure(IApplicationBuilder app)
{
//app.UseIISPlatformHandler();
//app.UseStaticFiles();
//app.UseMvc();
app.Run(async (objContext) =>
{
var cd = new System.Net.Mime.ContentDisposition {
FileName = "test.rar", Inline = false };
objContext.Response.Headers.Add("Content-Disposition", cd.ToString());
byte[] arr = System.IO.File.ReadAllBytes("G:\\test.rar");
await objContext.Response.Body.WriteAsync(arr, 0, arr.Length);
});
}
Run Code Online (Sandbox Code Playgroud)
但是当在Controller的动作中使用相同的代码时,app.Run被注释掉,保存弹出窗口没有出现,内容只是呈现为文本.
[Route("[controller]")]
public class SampleController : Controller
{
[HttpPost("DownloadFile")]
public void DownloadFile(string strData)
{
var cd = new System.Net.Mime.ContentDisposition {
FileName = "test.rar", Inline = false };
Response.Headers.Add("Content-Disposition", cd.ToString());
byte[] arr = System.IO.File.ReadAllBytes("G:\\test.rar");
Response.Body.WriteAsync(arr, 0, arr.Length);
Run Code Online (Sandbox Code Playgroud)
需要的是,控制流需要来到控制器,执行一些逻辑,然后将byte []响应内容发送到客户端,用户需要保存文件.没有cshtml,只是简单的html与jquery ajax调用.
你真的需要HttpPost属性吗?尝试删除它或使用HttpGet:
public async void DownloadFile()
{
Response.Headers.Add("content-disposition", "attachment; filename=test.rar");
byte[] arr = System.IO.File.ReadAllBytes(@"G:\test.rar");
await Response.Body.WriteAsync(arr, 0, arr.Length);
}
Run Code Online (Sandbox Code Playgroud)
更新:可能更容易使用FileStreamResult:
[HttpGet]
public FileStreamResult DownloadFile() {
Response.Headers.Add("content-disposition", "attachment; filename=test.rar");
return File(new FileStream(@"G:\test.rar", FileMode.Open),
"application/octet-stream"); // or "application/x-rar-compressed"
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9911 次 |
| 最近记录: |