Home >Backend Development >C#.Net Tutorial >.Net Core implementation example of downloading files

.Net Core implementation example of downloading files

黄舟
黄舟Original
2018-05-15 15:28:197343browse

This article will share with you the .NetCore download file. There are two common downloads: the A tag directly points to the download file address and the post or get request background output file stream. This article will also focus on these two methods. Come share; if it is helpful to you, please support it.

  • Allow sites to download files without recognizing the content-type (ie: download without mime type restrictions)

  • How to allow downloading of files with .nupkg and .apk suffixes

  • Razor template post download file example

  • Some thoughts and anxieties about using NetCore in the past six months

Allow sites to download files without recognizing content-type (ie: download without mime type restrictions)

For netcore web projects, there are some built-in content-type file types that allow downloading; we will use an ordinary razorweb project to take a look at the example of downloading excel directly through the connection; first, in the wwwroot directory of the project Create a bak folder, and then store the following files in this directory:

After passing the test, only the excel.xls file can be downloaded directly, and the others All are 404:

If you want files with suffixes such as .apk, .nupkg.cs etc. to not be restricted , we can pass public static IApplicationBuilder UseStaticFiles(this IApplicationBuilder app, StaticFileOptions options); extension to set, we just need to modify it to the following code:

            app.UseStaticFiles(new StaticFileOptions
            {                //设置不限制content-type
                ServeUnknownFileTypes = true 
            });

Then restart the operation. At this time, it will be no problem for us to access and download these files (Note that it is OK to download files with any suffix at this time), as shown in the screenshot below:

As for the files with cs suffix, which are displayed directly in the Google browser, there will be no pictures here. If you are interested, you can try it;

How to allow downloading. Files with nupkg and .apk suffixes

Through the above example, we can use ServeUnknownFileTypes = true; to directly set unlimited download file types, which is usually not It's too good or it's not allowed, or it's not often said to be unsafe; if we only need to add the download of .nupkg and .apk files with the suffix , then we can add the mime type through the following code, such as :

app.UseStaticFiles(new StaticFileOptions
            {                //ServeUnknownFileTypes = true 
                ContentTypeProvider = new FileExtensionContentTypeProvider(new Dictionary<string, string>
                {
                    { ".apk","application/vnd.android.package-archive"},
                    { ".nupkg","application/zip"}
                })
            });

Similarly, files with excel, apk, and nupkg suffixes can also be downloaded:

But this time we visit http://localhost:1120/bak/Startup.cs You will not get the downloaded content:

Because We did not add an extension type to the .cs file, so the system directly returned 404 to us; here we passed a mapping dic type through the constructor of the FileExtensionContentTypeProvider object to let the project know the content that is allowed to be downloaded- type type file;

Razor template post download file example

To be honest, I will study the Razor template when I have time recently. Below we will use her post form. Method of requesting the backend to download files; the code for the login.cshtml file is given directly below:

@page
@model LoginModel
@{}<form method="post">
    <button type="submit" asp-page-handler="down" class="btn">下载</button>
    <button type="submit" asp-page-handler="down01" class="btn">下载01</button>
    <button type="submit" asp-page-handler="down02" class="btn">下载02</button>
</form>

It is worth noting here that razor executes the request through asp-page-handler= end method, let’s take a look at what the final html code she generated looks like:

It can be seen that handler is mainly used as the parameter name. To pass the request's backend method, let's take a look at how the backend code is written (in order to facilitate the downloading of files, I take love.apk as an example):

/// <summary>
        /// 虚拟文件地址输出下载        
        /// </summary>
        /// <returns></returns>
        public IActionResult OnPostDown()
        {            
        var addrUrl = "/bak/love.apk";            
        return File(addrUrl, "application/vnd.android.package-archive", Path.GetFileName(addrUrl));
        }        
        /// <summary>
        /// 文件流的方式输出        /// </summary>
        /// <returns></returns>
        public IActionResult OnPostDown01()
        {            
        var addrUrl = @"D:\F\学习\vs2017\netcore\Study.AspNetCore\WebApp02-1\wwwroot\bak\love.apk";            
        var stream = System.IO.File.OpenRead(addrUrl);            
        return File(stream, "application/vnd.android.package-archive", Path.GetFileName(addrUrl));
        }        
        /// <summary>
        /// 通过HttpClient获取另外站点的文件流,再输出        
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> OnPostDown02()
        {            var path = "https://files.cnblogs.com/files/wangrudong003/%E7%89%B9%E4%BB%B701.gif";
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(path);            
            var stream = await client.GetStreamAsync(path);            
            return File(stream, "application/vnd.android.package-archive", Path.GetFileName(path));
        }

The three post acceptance methods on the backend are all FileStreamResult is also used to output the downloaded file. The difference is that the source of the file is different;

For simpler sites, the downloaded file generally exists in the site directory, which is somewhat similar to what I have here. wwwroot/bak directory, so it can be downloaded through the site virtual directory, which is our first download method;

Some sites generally exist on the same server disk of the web site for file security. , so you need to obtain the file stream through the second method here, and then pass it to File();

The last one is to transfer the files on your own other sites or other people's sites and output them as your own files. This method is also one of the hotlinking methods that people often say;

For the handler parameter of razor, what needs to be noted here is that it corresponds to the xxx name in the OnGetxxx or OnPostxxx method of our backend code. This is a razor request specification and must be followed. oh.

Some reflections and anxieties about using NetCore in the past six months

Impressions:

As of now, the latest version of netcore is 2.0, and its API is very powerful. Just a few projects I have done so far Judging from the use, her API support is very good; I have met before and someone asked me if there is an API for processing images. The answer is yes. Now there are many packages in the nuget package community that support image processing. Friends who are interested You can take a look at https://www.nuget.org/packages; after interspersing several projects, I deeply feel that the learning cost of netcore is actually not high. As far as netcore’s mvc project is concerned, as long as you know the mvc framework before, or It's a webform (personally I feel it corresponds to razor), so it's stress-free to use; here we recommend that some friends who dare not try netcore2.0 or those who think there is a learning cost may try it;

Anxiety:

netcore2.0 has been out for some time. During this period, although many friends have shared many related articles and git projects in the blog park; but they have responded or raised problems encountered in netcore development in three netqq groups. It seems that there are still very few, which makes people worried; of course, I know that several big names or some people at the company's technical decision-making level are also paying attention and starting to use this to start new projects; I don't know about other cities. There are many start-up companies in Beijing that use netcore as the starting point for their entrepreneurial projects, so I hope that friends or leaders who are still waiting on the sidelines will start taking action and work together to promote the development of the community.

The above is the detailed content of .Net Core implementation example of downloading files. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn