ASP.NET Core 1.0中实现文件上传的两种方式(提交表单和采用AJAX)

简介:

Bipin Joshi (http://www.binaryintellect.net/articles/f1cee257-378a-42c1-9f2f-075a3aed1d98.aspx)


Uploading files is a common requirement in web applications. In ASP.NET Core 1.0 uploading files and saving them on the server is quite easy. To that end this article shows how to do just that.Begin by creating a new ASP.NET Core project. Then add HomeController to the controllers folder. Then add UploadFiles view to Views > Home folder of the application.

HTML form for uploading files

Open the UploadFiles view and add the following HTML markup in it:

   1: <form asp-action="UploadFiles" 
   2:       asp-controller="Home" 
   3:       method="post"
   4:       enctype="multipart/form-data">
   5:     <input type="file" name="files" multiple />
   6:     <input type="submit" value="Upload Selected Files" />
   7: </form>

The above markup uses form tag helper of ASP.NET Core MVC. The asp-action attribute indicates that the form will be processed by the UploadFiles action upon submission. The asp-controller attribute specifies the name of the controller containing the action method. The form is submitted using POST method. The enctype attribute of the form is set to multipart/form-data indicating that it will be used for file upload operation.

The form contains an input field of type file. The name attribute of the file input field is set to files and the presence of multiple attribute indicates that multiple files can be uploaded at once. The submit button submits the form to the server.

If you run the application at this stage, the UploadFiles view should look like this:

Constructor and UploadFiles() GET action

Now, open the HomeController and add a constructor to it as shown below:

   1: public class HomeController : Controller
   2: {
   3:     private IHostingEnvironment hostingEnv;
   4:     public HomeController(IHostingEnvironment env)
   5:     {
   6:         this.hostingEnv = env;
   7:     }
   8: }

The constructor has a parameter of type IHostingEnvironment (Microsoft.AspNet.Hosting namespace). This parameter will be injected by MVC framework into the constructor. You need this parameter to construct the full path for saving the uploaded files. The IHostingEnvironment object is saved into a local variable for later use.

Then add UploadFiles() action for GET requests as shown below:

   1: public IActionResult UploadFiles()
   2: {
   3:     return View();
   4: }

UploadFiles() POST action

Finally, add UploadFiles() action for handling the POST requests.

   1: [HttpPost]
   2: public IActionResult UploadFiles(IList<IFormFile> files)
   3: {
   4:     long size = 0;
   5:     foreach(var file in files)
   6:     {
   7:         var filename = ContentDispositionHeaderValue
   8:                         .Parse(file.ContentDisposition)
   9:                         .FileName
  10:                         .Trim('"');
  11:         filename = hostingEnv.WebRootPath + $@"\{fileName}";
  12:         size += file.Length;
  13:         using (FileStream fs = System.IO.File.Create(filename))
  14:         {
  15:            file.CopyTo(fs);
  16:            fs.Flush();
  17:         }
  18:     }
  19:  
  20:     ViewBag.Message = $"{files.Count} file(s) / 
  21:                       {size} bytes uploaded successfully!";
  22:     return View();
  23: }

The UploadFiles() action has a parameter - IList<IFormFile> - to receive the uploaded files. The IFormFile object represents a single uploaded file. Inside, a size variable keeps track of how much data is being uploaded. Then a foreach loop iterates through the files collection.

The client side file name of an uploaded file is extracted using the ContentDispositionHeaderValue class (Microsoft.Net.Http.Headers namespace) and the ContentDisposition property of the IFormFile object. Let's assume that you wish to save the uploaded files into the wwwroot folder. So, to arrive at the full path you use the WebRootPath property of IHostingEnvironment and append the filename to it.

Finally, the file is saved by the code inside the using block. That code basically creates a new FileStream and copies the uploaded file into it. This is done using the Create() and the CopyTo() methods. A message is stored in ViewBag to be displayed to the end user.

The following figure shows a sample successful run of the application:

Using jQuery Ajax to upload the files

In the preceding example you used form POST to submit the files to the server. What if you wish to send files through Ajax? You can accomplish the task with a little bit of change to the <form> and the action.

Modify the <form> to have a plain push button instead of submit button as shown below:

   1: <form method="post" enctype="multipart/form-data">
   2:     <input type="file" id="files" 
   3:            name="files" multiple />
   4:     <input type="button" 
   5:            id="upload" 
   6:            value="Upload Selected Files" />
   7: </form>

Then add a <script> reference to the jQuery library and write the following code to handle the click event of the upload button:

   1: $(document).ready(function () {
   2:     $("#upload").click(function (evt) {
   3:         var fileUpload = $("#files").get(0);
   4:         var files = fileUpload.files;
   5:         var data = new FormData();
   6:         for (var i = 0; i < files.length ; i++) {
   7:             data.append(files[i].name, files[i]);
   8:         }
   9:         $.ajax({
  10:             type: "POST",
  11:             url: "/home/UploadFilesAjax",
  12:             contentType: false,
  13:             processData: false,
  14:             data: data,
  15:             success: function (message) {
  16:                 alert(message);
  17:             },
  18:             error: function () {
  19:                 alert("There was error uploading files!");
  20:             }
  21:         });
  22:     });
  23: });

The above code grabs each file from the file field and adds it to a FormData object (HTML5 feature). Then $.ajax() method POSTs the FormData object to the UploadFilesAjax() action of the HomeController. Notice that the contentType and processData properties are set to false since the FormData contains multipart/form-data content. The data property holds the FormData object.

Finally, add UploadFilesAjax() action as follows:

   1: [HttpPost]
   2: public IActionResult UploadFilesAjax()
   3: {
   4:     long size = 0;
   5:     var files = Request.Form.Files;
   6:     foreach (var file in files)
   7:     {
   8:         var filename = ContentDispositionHeaderValue
   9:                         .Parse(file.ContentDisposition)
  10:                         .FileName
  11:                         .Trim('"');
  12:         filename = hostingEnv.WebRootPath + $@"\{filename}";
  13:         size += file.Length;
  14:         using (FileStream fs = System.IO.File.Create(filename))
  15:         {
  16:            file.CopyTo(fs);
  17:            fs.Flush();
  18:         }
  19:     }
  20:     string message = $"{files.Count} file(s) / 
  21:                        {size} bytes uploaded successfully!";
  22:     return Json(message);
  23: }

The code inside UploadFilesAjax() is quite similar to UploadFiles() you wrote earlier. The main difference is how the files are received. The UploadFilesAjax() doesn't have IList<IFormFile> parameter. Instead it receives the files through the Request.Form.Files property. Secondly, the UploadFilesAjax() action returns a JSON string message to the caller for the sake of displaying in the browser.

That's it for now! Keep coding!!


作者:蒋金楠
微信公众账号:大内老A
微博: www.weibo.com/artech
如果你想及时得到个人撰写文章以及著作的消息推送,或者想看看个人推荐的技术资料,可以扫描左边二维码(或者长按识别二维码)关注个人公众号(原来公众帐号 蒋金楠的自媒体将会停用)。
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
相关文章
|
1月前
|
消息中间件 前端开发 小程序
一个基于.NET Core构建的简单、跨平台、模块化的商城系统
今天大姚给大家分享一个基于.NET Core构建的简单、跨平台、模块化、完全开源免费(MIT License)的商城系统:Module Shop。
|
1月前
|
算法 C# 数据库
【干货】一份10万字免费的C#/.NET/.NET Core面试宝典
C#/.NET/.NET Core相关技术常见面试题汇总,不仅仅为了面试而学习,更多的是查漏补缺、扩充知识面和大家共同学习进步。该知识库主要由自己平时学习实践总结、网上优秀文章资料收集(这一部分会标注来源)和社区小伙伴提供三部分组成。该份基础面试宝典完全免费,发布两年来收获了广大.NET小伙伴的好评,我会持续更新和改进,欢迎关注我的公众号【追逐时光者】第一时间获取最新更新的面试题内容。
|
4天前
|
开发框架 前端开发 JavaScript
ASP.NET AJAX使用方法概述(三)
ASP.NET AJAX使用方法概述(三)
10 1
|
5天前
|
开发框架 缓存 前端开发
安装ASP.NET AJAX (一安装)
安装ASP.NET AJAX (一安装)
10 0
|
19天前
|
开发框架 前端开发 JavaScript
JavaScript云LIS系统源码ASP.NET CORE 3.1 MVC + SQLserver + Redis医院实验室信息系统源码 医院云LIS系统源码
实验室信息系统(Laboratory Information System,缩写LIS)是一类用来处理实验室过程信息的软件,云LIS系统围绕临床,云LIS系统将与云HIS系统建立起高度的业务整合,以体现“以病人为中心”的设计理念,优化就诊流程,方便患者就医。
22 0
|
1月前
|
Linux API iOS开发
.net core 优势
.NET Core 的优势:跨平台兼容(Windows, macOS, Linux)及容器支持,高性能,支持并行版本控制,丰富的新增API,以及开源。
27 4
|
1月前
|
开发框架 人工智能 .NET
C#/.NET/.NET Core拾遗补漏合集(持续更新)
在这个快速发展的技术世界中,时常会有一些重要的知识点、信息或细节被忽略或遗漏。《C#/.NET/.NET Core拾遗补漏》专栏我们将探讨一些可能被忽略或遗漏的重要知识点、信息或细节,以帮助大家更全面地了解这些技术栈的特性和发展方向。
|
4月前
|
开发框架 前端开发 .NET
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
47 0
|
2月前
|
开发框架 前端开发 .NET
进入ASP .net mvc的世界
进入ASP .net mvc的世界
32 0
|
2月前
|
开发框架 前端开发 .NET
C# .NET面试系列六:ASP.NET MVC
<h2>ASP.NET MVC #### 1. MVC 中的 TempData\ViewBag\ViewData 区别? 在ASP.NET MVC中,TempData、ViewBag 和 ViewData 都是用于在控制器和视图之间传递数据的机制,但它们有一些区别。 <b>TempData:</b> 1、生命周期 ```c# TempData 的生命周期是短暂的,数据只在当前请求和下一次请求之间有效。一旦数据被读取,它就会被标记为已读,下一次请求时就会被清除。 ``` 2、用途 ```c# 主要用于在两个动作之间传递数据,例如在一个动作中设置 TempData,然后在重定向到另
120 5