ASP.NET Core應用:文件掃描上傳

微軟的東西愈來愈棒了,各類開源和跨平臺工具相繼推出。.NET Core終於讓.NET開始像Java同樣,能夠在任意平臺上運行代碼。最近學習了下微軟的教程,結合跨平臺的Dynamic Web TWAIN,分享下個人第一個ASP.NET Core "Hello World"。javascript

安裝

Hello World

如何初始化一個ASP.NET Core的工程?根據微軟的教程html

mkdir aspnetcoreapp
cd aspnetcoreapp
dotnet new -t web

建立的工程包含了不少的文件,已經比較複雜了。要搞明白髮生了什麼,仍是一步一步建立文件比較好。因此只須要用命令:java

dotnet new

這樣會建立一個命令行工程,包含兩個文件Program.csproject.json。我須要的是web server,因此修改下這兩個文件。git

Program.cs:github

using System.IO;
using aspnetcoreapp;
using Microsoft.AspNetCore.Hosting;
 
namespace ConsoleApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseStartup<Startup>()
                .Build();
 
            host.Run();
        }
    }
}

project.json:web

{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true
  },
  "dependencies": {},
  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.0.1"
        },
        "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
        "Microsoft.AspNetCore.StaticFiles": "1.0.0"
      },
      "imports": "dnxcore50"
    }
  }
}

這裏作的事情就是添加了web server Kestrel,以及經過當前路徑加載靜態文靜。還須要建立一個Startup.cs:json

using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
 
namespace aspnetcoreapp
{
    public class Startup
    {
        public void Configure(IApplicationBuilder app)
        {
            // app.UseDefaultFiles();
            // app.UseStaticFiles();
            app.UseFileServer();
        }
    }
}

UseFileServer等同與UseDefaultFiles+UseStaticFiles。默認加載wwwroot目錄下的靜態文件,並把index.html看成首頁。固然你能夠經過代碼去修改路徑。若是如今部署靜態html文件,已經能夠訪問了。瀏覽器

爲了讓server端作一點事情,作一個文件上傳功能。首先須要映射一下路徑,好比上傳的url是www.xxx.com/upload。打開index.html作一下修改:bash

var strActionPage = CurrentPath + "upload";

一旦知足條件就能夠執行操做:app

using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
 
namespace aspnetcoreapp
{
    public class Startup
    {
        public void Configure(IApplicationBuilder app)
        {
            // app.UseDefaultFiles();
            // app.UseStaticFiles();
            app.UseFileServer();
 
            app.Map("/upload", UploadFile);
        }
 
        private static void UploadFile(IApplicationBuilder app)
        {
            app.Run(async context =>
            {
                var files = context.Request.Form.Files;
                var uploads = Path.Combine(Directory.GetCurrentDirectory(), "uploads");
                if (!Directory.Exists(uploads)) {
                    Directory.CreateDirectory(uploads);
                }
 
                foreach (var file in files)
                {
                    var filename = file.FileName;
                    using (var fileStream = new FileStream(Path.Combine(uploads, filename), FileMode.Create))
                    {
                        await file.CopyToAsync(fileStream);
                    }
                }
            });
        }
    }
}

如今能夠運行下程序:

dotnet restore
dotnet run

瀏覽器中打開localhost:5000看到的效果:

MVC

如今用MVC來改造下上面的代碼。首先在project.json中添加新的依賴:

{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true
  },
  "dependencies": {},
  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.0.1"
        },
        "Microsoft.AspNetCore.Mvc": "1.0.1",
        "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
        "Microsoft.AspNetCore.StaticFiles": "1.0.0"
      },
      "imports": "dnxcore50"
    }
  },
 
  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  }
}

在Startup.cs中添加MVC服務:

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
 
namespace aspnetcoreapp
{
    public class Startup
    {
        public void Configure(IApplicationBuilder app)
        {
            app.UseStaticFiles();
 
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
 
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }
    }
}

MVC中使用了路徑模版。默認狀況下須要一個HomeController.cs:

using Microsoft.AspNetCore.Mvc;
 
namespace aspnetcoreapp.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}

這個文件放在Controller目錄下。對應的還有一個Index.cshtml文件,放在Views/Home目錄下。把以前的那個index.html改一下名就能夠了。

由於上傳的URL是www.xxx.com/upload,相對的也要建立一個Controller/UploadController.cs:

using Microsoft.AspNetCore.Mvc;
using System.IO;
 
namespace aspnetcoreapp.Controllers
{
    public class UploadController : Controller
    {
        [HttpPost]
        public void Index()
        {
            var files = Request.Form.Files;
            var uploads = Path.Combine(Directory.GetCurrentDirectory(), "uploads");
            if (!Directory.Exists(uploads))
            {
                Directory.CreateDirectory(uploads);
            }
 
            foreach (var file in files)
            {
                var filename = file.FileName;
                using (var fileStream = new FileStream(Path.Combine(uploads, filename), FileMode.Create))
                {
                    file.CopyTo(fileStream);
                    fileStream.Flush();
                }
            }
        }
    }
}

這樣就完成了。

源碼

https://github.com/dynamsoft-dwt/ASP.NET-Core

相關文章
相關標籤/搜索