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:
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyBpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBXaW5kb3dzIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOkJDQzA1MTVGNkE2MjExRTRBRjEzODVCM0Q0NEVFMjFBIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOkJDQzA1MTYwNkE2MjExRTRBRjEzODVCM0Q0NEVFMjFBIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6QkNDMDUxNUQ2QTYyMTFFNEFGMTM4NUIzRDQ0RUUyMUEiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6QkNDMDUxNUU2QTYyMTFFNEFGMTM4NUIzRDQ0RUUyMUEiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz6p+a6fAAAAD0lEQVR42mJ89/Y1QIABAAWXAsgVS/hWAAAAAElFTkSuQmCC" alt="" />
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:
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyBpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBXaW5kb3dzIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOkJDQzA1MTVGNkE2MjExRTRBRjEzODVCM0Q0NEVFMjFBIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOkJDQzA1MTYwNkE2MjExRTRBRjEzODVCM0Q0NEVFMjFBIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6QkNDMDUxNUQ2QTYyMTFFNEFGMTM4NUIzRDQ0RUUyMUEiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6QkNDMDUxNUU2QTYyMTFFNEFGMTM4NUIzRDQ0RUUyMUEiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz6p+a6fAAAAD0lEQVR42mJ89/Y1QIABAAWXAsgVS/hWAAAAAElFTkSuQmCC" alt="" />
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!!
ASP.NET Core 1.0中实现文件上传的两种方式(提交表单和采用AJAX)的更多相关文章
- curl文件上传有两种方式,一种是post_fileds,一种是infile
curl文件上传有两种方式,一种是POSTFIELDS,一种是INFILE,POSTFIELDS传递@实际地址,INFILE传递文件流句柄! );curl_setopt($ch, CURLOPT_PO ...
- 用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 第三 ...
- Asp.Net Core 2.0 WebUploader FastDfs 文件上传 分段上传
功能点: 1. 使用.net core 2.0 实现文件上传 2. 使用webuploader实现单文件,多文件上传 3. 使用webuploader实现大文件的分段上传. 4. 使用webuploa ...
- 利用Selenium实现图片文件上传的两种方式介绍
在实现UI自动化测试过程中,有一类需求是实现图片上传,这种需求根据开发的实现方式,UI的实现方式也会不同. 一.直接利用Selenium实现 这种方式是最简单的一种实现方式,但是依赖于开发的实现. 当 ...
- ASP.NET Core WEB API 使用element-ui文件上传组件el-upload执行手动文件文件,并在文件上传后清空文件
前言: 从开始学习Vue到使用element-ui-admin已经有将近快两年的时间了,在之前的开发中使用element-ui上传组件el-upload都是直接使用文件选取后立即选择上传,今天刚好做了 ...
- java模拟表单上传文件,java通过模拟post方式提交表单实现图片上传功能实例
java模拟表单上传文件,java通过模拟post方式提交表单实现图片上传功能实例HttpClient 测试类,提供get post方法实例 package com.zdz.httpclient; i ...
- Java文件上传的几种方式
文件上传与文件上传一样重要.在Java中,要实现文件上传,可以有两种方式: 1.通过Servlet类上传 2.通过Struts框架实现上传 这两种方式的根本还是通过Servlet进行IO流的操作. 一 ...
- web 文件上传的几种方式
问题 文件上传在WEB开发中应用很广泛. 文件上传是指将本地图片.视频.音频等文件上传到服务器上,可以供其他用户浏览或下载的过程. 以下总结了常见的文件(图片)上传的方式和要点处理. 表单上传 这是传 ...
- 基础教程:上传/下载ASP.NET Core 2.0中的文件
问题 如何上传和下载ASP.NET Core MVC中的文件. 解 在一个空的项目中,更新 Startup 类以添加MVC的服务和中间件. publicvoid ConfigureServices( ...
随机推荐
- Tomcat一个BUG造成CLOSE_WAIT
之前应该提过,我们线上架构整体重新架设了,应用层面使用的是Spring Boot,前段日子因为一些第三方的原因,略有些匆忙的提前开始线上的内测了.然后运维发现了个问题,服务器的HTTPS端口有大量的C ...
- Angular2入门系列教程3-多个组件,主从关系
上一篇 Angular2项目初体验-编写自己的第一个组件 好了,前面简单介绍了Angular2的基本开发,并且写了一个非常简单的组件,这篇文章我们将要学会编写多个组件并且有主从关系 现在,假设我们要做 ...
- 札记:Fragment基础
Fragment概述 在Fragment出现之前,Activity是app中界面的基本组成单位,值得一提的是,作为四大组件之一,它是需要"注册"的.组件的特性使得一个Activit ...
- C++中的变长参数
新参与的项目中,为了使用共享内存和自定义内存池,我们自己定义了MemNew函数,且在函数内部对于非pod类型自动执行构造函数.在需要的地方调用自定义的MemNew函数.这样就带来一个问题,使用stl的 ...
- Ubuntu 16.10 安装byzanz截取动态效果图工具
1.了解byzanz截取动态效果图工具 byzanz能制作文件小,清晰的GIF动态效果图,不足就是,目前只能通过输入命令方式来录制. byzanz主要的参数选项有: -d, --duration=SE ...
- WPF做12306验证码点击效果
一.效果 和12306是一样的,运行一张图上点击多个位置,横线以上和左边框还有有边框位置不允许点击,点击按钮输出坐标集合,也就是12306登陆的时候,需要向后台传递的参数. 二.实现思路 1.获取验证 ...
- javascript之Object.defineProperty的奥妙
直切主题 今天遇到一个这样的功能: 写一个函数,该函数传递两个参数,第一个参数为返回对象的总数据量,第二个参数为初始化对象的数据.如: var o = obj (4, {name: 'xu', age ...
- 基于AOP的MVC拦截异常让代码更优美
与asp.net 打交道很多年,如今天微软的优秀框架越来越多,其中微软在基于mvc的思想架构,也推出了自己的一套asp.net mvc 框架,如果你亲身体验过它,会情不自禁的说‘漂亮’.回过头来,‘漂 ...
- 用WebRequest +HtmlAgilityPack 从外网抓取数据到本地
相信大家对于WebRequest 并不陌生,我们在C#中发请求的方式,就是创建一个WebRequest .那么如果我们想发一个请求到外网,比如国内上不了的一些网站,那么该怎么做呢? 其实WebRequ ...
- windows环境redis主从安装部署
准备工作 下载windows环境redis,我下载的是2.4.5,解压,拷贝一主(master)两从(slaveof).主机端口使用6379,两从的端口分别为6380和6381, 我本地索性用6379 ...