[英]How to download a file in ASP.NET Core?
在 MVC 中,我们使用以下代码下载文件。 在 ASP.NET core 中,如何实现呢?
HttpResponse response = HttpContext.Current.Response;
System.Net.WebClient net = new System.Net.WebClient();
string link = path;
response.ClearHeaders();
response.Clear();
response.Expires = 0;
response.Buffer = true;
response.AddHeader("Content-Disposition", "Attachment;FileName=a");
response.ContentType = "APPLICATION/octet-stream";
response.BinaryWrite(net.DownloadData(link));
response.End();
您的控制器应该返回一个IActionResult
,并使用File
方法,例如:
[HttpGet("download")]
public IActionResult GetBlobDownload([FromQuery] string link)
{
var net = new System.Net.WebClient();
var data = net.DownloadData(link);
var content = new System.IO.MemoryStream(data);
var contentType = "APPLICATION/octet-stream";
var fileName = "something.bin";
return File(content, contentType, fileName);
}
您可以尝试以下代码来下载文件。 它应该返回FileResult
public ActionResult DownloadDocument()
{
string filePath = "your file path";
string fileName = "your file name";
byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
return File(fileBytes, "application/force-download", fileName);
}
一个相对简单的方法是使用内置的PhysicalFile
结果,它适用于所有控制器: MS Docs:PhysicalFile
一个简单的例子:
public IActionResult DownloadFile(string filePath)
{
return PhysicalFile(filePath, MimeTypes.GetMimeType(filePath), Path.GetFileName(filePath));
}
当然,出于安全考虑,您永远不应该公开这种 API。
我通常将实际文件路径屏蔽在友好标识符后面,然后我用它来查找真实文件路径(如果传入了无效 ID,则返回 404),即:
[HttpGet("download-file/{fileId}")]
public IActionResult DownloadFile(int fileId)
{
var filePath = GetFilePathFromId(fileId);
if (filePath == null) return NotFound();
return PhysicalFile(filePath, MimeTypes.GetMimeType(filePath), Path.GetFileName(filePath));
}
对于那些好奇的人, MimeTypes
助手是来自 MimeKit 的一个很棒的小Nuget包
这是我的 Medium 文章,逐步描述所有内容(还包括 GitHub 存储库): https ://medium.com/@tsafadi/download-a-file-with-asp-net-core-e23e8b198f74
任何方式这都是控制器的外观:
[HttpGet]
public IActionResult DownloadFile()
{
// Since this is just and example, I am using a local file located inside wwwroot
// Afterwards file is converted into a stream
var path = Path.Combine(_hostingEnvironment.WebRootPath, "Sample.xlsx");
var fs = new FileStream(path, FileMode.Open);
// Return the file. A byte array can also be used instead of a stream
return File(fs, "application/octet-stream", "Sample.xlsx");
}
视图内部:
$("button").click(function () {
var xhr = new XMLHttpRequest();
xhr.open("GET", "Download/DownloadFile", true);
xhr.responseType = "blob";
xhr.onload = function (e) {
if (this.status == 200) {
var blob = this.response;
/* Get filename from Content-Disposition header */
var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}
// This does the trick
var a = document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.download = filename;
a.dispatchEvent(new MouseEvent('click'));
}
}
xhr.send();
});
创建一个服务,比如 FileService。
public class FileService
{
private readonly IHostingEnvironment _hostingEnvironment;
constructor(IHostingEnvironment hostingEnvironment)
{
this._hostingEnvironment = hostingEnvironment;
}
}
向文件的 FileService MimeType 添加方法
private string GetMimeType(string fileName)
{
// Make Sure Microsoft.AspNetCore.StaticFiles Nuget Package is installed
var provider = new FileExtensionContentTypeProvider();
string contentType;
if (!provider.TryGetContentType(fileName, out contentType))
{
contentType = "application/octet-stream";
}
return contentType;
}
现在添加一个下载文件的方法,
public FileContentResult GetFile(string filename)
{
var filepath = Path.Combine($"{this._environment.WebRootPath}\\path-to-required-folder\\{filename}");
var mimeType = this.GetMimeType(filename);
byte[] fileBytes;
if (File.Exists(filepath))
{
fileBytes = File.ReadAllBytes(filepath);
}
else
{
// Code to handle if file is not present
}
return new FileContentResult(fileBytes, mimeType)
{
FileDownloadName = filename
};
}
现在添加控制器方法并在 FileService 中调用 GetFile 方法,
public IActionResult DownloadFile(string filename)
{
// call GetFile Method in service and return
}
Asp.net Core 2.1+ 示例(最佳实践)
启动.cs:
private readonly IHostingEnvironment _env;
public Startup(IConfiguration configuration, IHostingEnvironment env)
{
Configuration = configuration;
_env = env;
}
services.AddSingleton(_env.ContentRootFileProvider); //Inject IFileProvider
SomeService.cs:
private readonly IFileProvider _fileProvider;
public SomeService(IFileProvider fileProvider)
{
_fileProvider = fileProvider;
}
public FileStreamResult GetFileAsStream()
{
var stream = _fileProvider
.GetFileInfo("RELATIVE PATH TO FILE FROM APP ROOT")
.CreateReadStream();
return new FileStreamResult(stream, "CONTENT-TYPE")
}
控制器将返回IActionResult
[HttpGet]
public IActionResult Get()
{
return _someService.GetFileAsStream() ?? (IActionResult)NotFound();
}
Action 方法需要返回带有文件流、字节[] 或虚拟路径的 FileResult。 您还需要知道正在下载的文件的内容类型。 这是一个示例(快速/脏)实用程序方法。 示例视频链接如何使用 asp.net core 下载文件
[Route("api/[controller]")]
public class DownloadController : Controller
{
[HttpGet]
public async Task<IActionResult> Download()
{
var path = @"C:\Vetrivel\winforms.png";
var memory = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
var ext = Path.GetExtension(path).ToLowerInvariant();
return File(memory, GetMimeTypes()[ext], Path.GetFileName(path));
}
private Dictionary<string, string> GetMimeTypes()
{
return new Dictionary<string, string>
{
{".txt", "text/plain"},
{".pdf", "application/pdf"},
{".doc", "application/vnd.ms-word"},
{".docx", "application/vnd.ms-word"},
{".png", "image/png"},
{".jpg", "image/jpeg"},
...
};
}
}
[HttpGet]
public async Task<FileStreamResult> Download(string url, string name, string contentType)
{
var stream = await new HttpClient().GetStreamAsync(url);
return new FileStreamResult(stream, contentType)
{
FileDownloadName = name,
};
}
我的方式很短,我认为它适合大多数人的需要。
[HttpPost]
public ActionResult Download(string filePath, string fileName)
{
var fileBytes = System.IO.File.ReadAllBytes(filePath);
new FileExtensionContentTypeProvider().TryGetContentType(Path.GetFileName(filePath), out var contentType);
return File(fileBytes, contentType ?? "application/octet-stream", fileName);
}
这对我有用:
httpContext.Response.Headers.Append("content-disposition", "attachment;filename=" + mytextfilename);
httpContext.Response.ContentType = "application/text";
httpContext.Response.WriteAsync(mytextfile);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.