ezi*_*ile 11 c# asp.net-mvc response httpcontext
我正在将数据从服务器传输到客户端以供下载使用filestream.write.在这种情况下,发生的事情是我能够下载该文件,但它不会在我的浏览器中显示为下载."另存为"弹出窗口不会出现在"下载"部分中的"下载栏"中.从四处查看,我想我需要在响应标题中包含"something"来告诉浏览器这个响应有一个附件.我也想设置cookie.要做到这一点,这就是我在做的事情:
[HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=" & name)]
public ActionResult Download(string name)
{
// some more code to get data in inputstream.
using (FileStream fs = System.IO.File.OpenWrite(TargetFile))
{
byte[] buffer = new byte[SegmentSize];
int bytesRead;
while ((bytesRead = inputStream.Read(buffer, 0, SegmentSize)) > 0)
{
fs.WriteAsync(buffer, 0, bytesRead);
}
}
}
return RedirectToAction("Index");
}
Run Code Online (Sandbox Code Playgroud)
我收到错误:"System.web.httpcontext.current是一个属性,用作类型."
我在正确的位置更新标题吗?有没有其他方法可以做到这一点?
PSL*_*PSL 13
是的,你这样做是错误的尝试这个,你应该在你的行动中添加标题而不是作为方法的属性标题.
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=" & name)
Run Code Online (Sandbox Code Playgroud)
要么
Request.RequestContext.HttpContext.Response.AddHeader("Content-Disposition", "Attachment;filename=" & name)
Run Code Online (Sandbox Code Playgroud)
更新 据我所知,您正在通过直接调用操作对您的控制器/操作进行ajax调用,这对于文件下载不起作用.你可以通过这种方式实现它.
public void Download(string name)
{
//your logic. Sample code follows. You need to write your stream to the response.
var filestream = System.IO.File.ReadAllBytes(@"path/sourcefilename.pdf");
var stream = new MemoryStream(filestream);
stream.WriteTo(Response.OutputStream);
Response.AddHeader("Content-Disposition", "Attachment;filename=targetFileName.pdf");
Response.ContentType = "application/pdf";
}
Run Code Online (Sandbox Code Playgroud)
要么
public FileStreamResult Download(string name)
{
var filestream = System.IO.File.ReadAllBytes(@"path/sourcefilename.pdf");
var stream = new MemoryStream(filestream);
return new FileStreamResult(stream, "application/pdf")
{
FileDownloadName = "targetfilename.pdf"
};
}
Run Code Online (Sandbox Code Playgroud)
在JS按钮单击中,您可以执行与此类似的操作.
$('#btnDownload').click(function () {
window.location.href = "controller/download?name=yourargument";
});
Run Code Online (Sandbox Code Playgroud)
请在这里看看。
以下是从引用的网站上获取的。
public FileStreamResult StreamFileFromDisk()
{
string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/";
string fileName = "test.txt";
return File(new FileStream(path + fileName, FileMode.Open), "text/plain", fileName);
}
Run Code Online (Sandbox Code Playgroud)
编辑1:
通过我们的优质服务添加您可能更感兴趣的产品。您可以在此处检查完整的细节。
public ActionResult Download()
{
var document = ...
var cd = new System.Net.Mime.ContentDisposition
{
// for example foo.bak
FileName = document.FileName,
// always prompt the user for downloading, set to true if you want
// the browser to try to show the file inline
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(document.Data, document.ContentType);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
51799 次 |
| 最近记录: |