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!!

时间: 2024-08-04 03:53:10

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

用VSCode开发一个asp.net core2.0+angular5项目(5): Angular5+asp.net core 2.0 web api文件上传

第一部分: http://www.cnblogs.com/cgzl/p/8478993.html 第二部分: http://www.cnblogs.com/cgzl/p/8481825.html 第三部分: https://www.cnblogs.com/cgzl/p/8525541.html 第四部分: https://www.cnblogs.com/cgzl/p/8536350.html 这部分就讲从angular5的客户端上传图片到asp.net core 2.0的 web api. 这是

SpringMVC文件上传的两种方式

搞JavaWEB的应该或多或少都做过文件上传,之前也做过简单的上传,但是如下的需求也确实把我为难了一把: 1.上传需要异步, 2.需要把上传后文件的地址返回来, 3.需要进度条显示上传进度. 项目使用SpringMVC架构+easyUI,初步分析,进度条可以使用easyui自带的进度条,上传可以使用ajaxFileUpload或者ajaxForm.文件传上去,然后把路径带回来是没问题的,关键是上传进度怎么获取.最终,两种方式都实现啦. 首先,不管哪种方式,后台对文件处理都是必须的.文件处理: 1

利用Selenium实现图片文件上传的两种方式介绍

在实现UI自动化测试过程中,有一类需求是实现图片上传,这种需求根据开发的实现方式,UI的实现方式也会不同. 一.直接利用Selenium实现 这种方式是最简单的一种实现方式,但是依赖于开发的实现. 当开发直接使用file类型的input实现图片文件的上传时,实例:<input type="file" name=''filename"> 我们可以直接利用Selenium提供的方法实现文件上传,但是因为依赖开发的实现,而且目前实现基本都会利用框架,所以这种实现方式有很

ASP.NET Core WEB API 使用element-ui文件上传组件el-upload执行手动文件文件,并在文件上传后清空文件

前言: 从开始学习Vue到使用element-ui-admin已经有将近快两年的时间了,在之前的开发中使用element-ui上传组件el-upload都是直接使用文件选取后立即选择上传,今天刚好做了一个和之前类似的文件选择上传的需求,不过这次是需要手动点击按钮把文件上传到服务器中进行数据导入,而且最多只能够选择一个文件进行上传,上传成功后需要对file-list中的文件列表数据进行清空操作,在这里服务端使用的是ASP.NET Core WEB API来进行文件流数据接收和保存. 一.简单概述e

文件上传的三种方式-Java

前言:因自己负责的项目(jetty内嵌启动的SpringMvc)中需要实现文件上传,而自己对java文件上传这一块未接触过,且对 Http 协议较模糊,故这次采用渐进的方式来学习文件上传的原理与实践.该博客重在实践. 一.Http协议原理简介 HTTP是一个属于应用层的面向对象的协议,由于其简捷.快速的方式,适用于分布式超媒体信息系统.它于1990年提出,经过几年的使用与发展,得到不断地完善和扩展.目前在WWW中使用的是HTTP/1.0的第六版,HTTP/1.1的规范化工作正在进行之中,而且HT

Java文件上传的几种方式

文件上传与文件上传一样重要.在Java中,要实现文件上传,可以有两种方式: 1.通过Servlet类上传 2.通过Struts框架实现上传 这两种方式的根本还是通过Servlet进行IO流的操作. 一.通过Servlet类上传 1.编写Sevlet类 package com.chanshuyi.upload; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.

关于文件上传的几种方式

上传之前 JavaScript 检测 1:javascript判断上传文件的大小: 在FireFox.Chrome浏览器中可以根据document.getElementById(“idoffile”).size 获取上传文件的大小(字节数),而IE浏览器中不支持该属性,只能借助标签的dynsrc属性,来间接实现获取文件的大小(但需要同意ActiveX控件的运行). var ua = window.navigator.userAgent; if (ua.indexOf("MSIE")&g

C#实现Web文件上传的两种方法

1. C#实现Web文件的上传 在Web编程中,我们常需要把一些本地文件上传到Web服务器上,上传后,用户可以通过浏览器方便地浏览这些文件,应用十分广泛. 那么使用C#如何实现文件上传的功能呢?下面笔者简要介绍一下. 首先,在你的Visual C# web project 中增加一个上传用的Web Form,为了要上传文件,需要在ToolBox中选择HTML类的File Field控件,将此控件加入到Web Form中,然而此时该控件还不是服务端控件,我们需要为它加上如下一段代码:<input

ajax以及文件上传的几种方式

方式一:通过form表单中,html input 标签的“file”完成 # 前端代码uoload.html <form method="post" action="/upload/" enctype="multipart/form-data"> <input id="user" type="text" name="user" /> <input id='i