In ASP.NET Core, files can be added to a static directory for direct download. However, this method may not be secure or flexible enough.
We can add an action in the Controller to access any file on the server through this action.
Action Format
public FileResult Down() { return File(xxx,xxx,xxx); }
Returns FileResult type, File() object
It's that simple.
File() Object
The question is how to write this File() object
Here's an example from the author
Under 100% error-free conditions, the file path is F:\a.txt
1. Create a FileStream
2. Get the file type Content-Type, which can either be obtained programmatically or filled in as a string
3. Set the file name
var stream = System.IO.File.OpenRead(“F:\a.txt”); // Create file stream
The file type for .txt is text/plain
Set the file name to b.txt
Then the returned File code is as follows
return File(stream, "text/plain", “b.txt");
It's that simple.
Getting the File Type
You can refer to C# for getting the file type
http://www.cnblogs.com/zzsdream/articles/5796763.html
About the corresponding Context-Type of file types
http://tool.oschina.net/commons/
The author attaches a small method
//Import using System.IO; var contentype = MimeMapping.GetMimeMapping(fileName); // Get file type
Dynamic File Retrieval
public FileResult DownSH(string DownM) // The file code to download { var path = _sqlContext.jexusSqls.FirstOrDefault(a => a.DownM == DownM.ToString()).FilePath; // Find the file address in the database if (!System.IO.File.Exists(path)) return null;</span><span style="color: #0000ff;">var</span> stream = <span style="color: #000000;">System.IO.File.OpenRead(path); // Create file stream </span><span style="color: #0000ff;">return</span> File(stream, <span style="color: #800000;">"</span><span style="color: #800000;">application/x-sh</span><span style="color: #800000;">"</span>, DownM+<span style="color: #800000;">"</span><span style="color: #800000;">.sh</span><span style="color: #800000;">"</span><span style="color: #000000;">); }</span></pre>
There are many ways to write, you just need to address the three core elements of file stream, file type, and file name.
文章评论