下载.net MVC中的文件
本文关键字:文件 MVC net 下载 | 更新日期: 2023-09-27 17:53:44
我想在我的网站上下载一个文件。
我代码:var uploadPath = HttpContext.Current.Server.MapPath("~/Content/upload/products/");
var response = new HttpResponseMessage();
var stream =new FileStream(uploadPath + "''" + fileName, FileMode.Open, FileAccess.Read);
response.Headers.AcceptRanges.Add("bytes");
response.StatusCode = HttpStatusCode.OK;
response.Content = new StreamContent(stream);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = Path.GetFileName(uploadPath + "''" + fileName)
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return response;
但是我在浏览器上看不到文件下载的进度。请帮帮我!
如果在响应返回之前文件流被关闭,您可以将其复制到内存流并使用它。
var uploadPath = HttpContext.Current.Server.MapPath("~/Content/upload/products/");
var stream = new FileStream(uploadPath + "''" + fileName, FileMode.Open, FileAccess.Read);
var memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
//content length for header
var contentLength = memoryStream.Length;
var response = new HttpResponseMessage();
response.Headers.AcceptRanges.Add("bytes");
response.StatusCode = HttpStatusCode.OK;
response.Content = new StreamContent(memoryStream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentLength = contentLength;
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = Path.GetFileName(uploadPath + "''" + fileName)
};
return response;