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:

<form asp-action="UploadFiles"
asp-controller="Home"
method="post"
enctype="multipart/form-data">
<input type="file" name="files" multiple />
<input type="submit" value="Upload Selected Files" />
</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:

public class HomeController : Controller
{
private IHostingEnvironment hostingEnv; public HomeController(IHostingEnvironment env)
{
this.hostingEnv = env;
}
}

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:

public IActionResult UploadFiles()
{
return View();
}

UploadFiles() POST action

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

[HttpPost]
public IActionResult UploadFiles(IList<IFormFile> files)
{
long size = 0;
foreach(var file in files)
{
var filename = ContentDispositionHeaderValue
.Parse(file.ContentDisposition)
.FileName
.Trim('"');
filename = hostingEnv.WebRootPath + $@"\{fileName}";
size += file.Length;
using (FileStream fs = System.IO.File.Create(filename))
{
file.CopyTo(fs);
fs.Flush();
}
}
ViewBag.Message = $"{files.Count} file(s) /
{size} bytes uploaded successfully!";
return View();
}

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:

<form method="post" enctype="multipart/form-data">
<input type="file" id="files"
name="files" multiple />
<input type="button"
id="upload"
value="Upload Selected Files" />

</form>

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

$(document).ready(function () {
$("#upload").click(function (evt) {
var fileUpload = $("#files").get(0);
var files = fileUpload.files;
var data = new FormData();
for (var i = 0; i < files.length ; i++) {
data.append(files[i].name, files[i]);
}
$.ajax({
type: "POST",
url: "/home/UploadFilesAjax",
contentType: false,
processData: false,
data: data,
success: function (message) {
alert(message);
},
error: function () {
alert("There was error uploading files!");
}
});
});
});

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:

[HttpPost]
public IActionResult UploadFilesAjax()
{
long size = 0;
var files = Request.Form.Files;
foreach (var file in files)
{
var filename = ContentDispositionHeaderValue
.Parse(file.ContentDisposition)
.FileName
.Trim('"');
filename = hostingEnv.WebRootPath + $@"\{filename}";
size += file.Length;
using (FileStream fs = System.IO.File.Create(filename))
{
file.CopyTo(fs);
fs.Flush();
}
}
string message = $"{files.Count} file(s) /
{size} bytes uploaded successfully!";
return Json(message);
}

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

Upload Files In ASP.NET Core 1.0 (Form POST And JQuery Ajax)的更多相关文章

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

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

  2. 用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 第三 ...

  3. [Asp.net core 2.0]Ueditor 图片上传

    摘要 在项目中要用到富文本编辑器,包含上传图片,插入视频等功能.但ueditor只有.net版本,没有支持core.那么上传等接口就需要自己实现了. 一个例子 首先去百度ueditor官网下载简化版的 ...

  4. ASP.NET Core 1.0 入门——了解一个空项目

    var appInsights=window.appInsights||function(config){ function r(config){t[config]=function(){var i= ...

  5. #ASP.NET Core 1.0 Key Features

    Cross platform support and flexible runtime engine(跨平台支持和灵活的运行时引擎) ASP.NET Core 1.0 offers support f ...

  6. 【原生态跨平台:ASP.NET Core 1.0(非Mono)在 Ubuntu 14.04 服务器上一对一的配置实现-篇幅1】

    鸡冻人心的2016,微软高产年. build 2016后 各种干货层出不穷. 1 Win10 集成了bash  ,实现了纳德拉的成诺,Microsoft Love Linux!!! 2 跨平台  ,收 ...

  7. Amazing ASP.NET Core 2.0

    前言 ASP.NET Core 的变化和发展速度是飞快的,当你发现你还没有掌握 ASP.NET Core 1.0 的时候, 2.0 已经快要发布了,目前 2.0 处于 Preview 1 版本,意味着 ...

  8. 从头编写 asp.net core 2.0 web api 基础框架 (1)

    工具: 1.Visual Studio 2017 V15.3.5+ 2.Postman (Chrome的App) 3.Chrome (最好是) 关于.net core或者.net core 2.0的相 ...

  9. 【转载】从头编写 asp.net core 2.0 web api 基础框架 (1)

    工具: 1.Visual Studio 2017 V15.3.5+ 2.Postman (Chrome的App) 3.Chrome (最好是) 关于.net core或者.net core 2.0的相 ...

随机推荐

  1. Eclipse下关于The serializable class UsersServlet does not declare a static final serialVersionUID field of type的警告

    The serializable class XXX does not declare a static final serialVersionUID field of type long seria ...

  2. python:利用pymssql模块操作SQL server数据库

    python默认的数据库是 SQLlite,不过它对MySql以及SQL server的支持也可以.这篇博客,介绍下如何在Windows下安装pymssql库并进行连接使用... 环境:Windows ...

  3. 【原创】jssh linux scp ssh 免密登录开源工具

    项目名 JSSH git地址: https://gitee.com/chejiangyi/jssh 项目介绍 linux scp(文件上传,下载) shell命令的java ssh jar和linux ...

  4. macOS10.14 Mojave无法打开和预览jpg的解决方法

    分析:之所以会出现这样的问题.是因为你用了独显 而没有驱动核显导致的.想要预览正常只要用核显或者开启核显加速就OK了就可以正常预览了. 解决办法:换无核显的机型试试,比如MacPro6.1,iMac ...

  5. Java内存模型与线程安全

    原文链接:blog.edreamoon.com Java内存模型 计算机cpu的运算能力强大,但是数据的存储相对于cpu运算能力需要消耗大量时间,为了充分利用运算能力引入了缓存,但是也为计算机系统带来 ...

  6. UVA10838 The Pawn Chess

    UVA好题没人写系列,感觉可以稍稍练习一下面向对象编程的形式(大雾) 题意很简单,在国际象棋的棋盘中有一些兵,走到对方底线即为胜利,问最优决策下谁能获胜.并输出最小步数. 首先这里的棋盘都只有\(4\ ...

  7. Jlink使用技巧之读取STM32内部的程序

    前言 上一篇Jlink系列文章介绍了如何使用J-Flash来下载Hex或Bin文件到单片机,具体可参考Jlink使用技巧之单独下载HEX文件到单片机,本篇文章介绍,如何使用JFlash来读取单片机的程 ...

  8. 生产者消费者 ProducerConsumer

    生产者消费者是常见的同步问题.一个队列,头部生产数据,尾部消费数据,队列的长度为固定值.当生产的速度大于消费的速度时,队列逐渐会填满,这时就会阻塞住.当尾部消费了数据之后,生产者就可以继续生产了. 生 ...

  9. 谈谈自己体会到的HTML5

    # 谈谈自己体会到的HTML5 很多介绍HTML5的文章,都是从以下几个方面去介绍的:语义化.丰富的表单.本地存储.多媒体.地理位置等等.纸上得来终觉浅,现在有了一定的实践经验之后,本人对其有了更加深 ...

  10. 微信支付异常:appid and openid not match

    上周调试微信小程序支付时遇到的问题,在调用统一下单接口获取微信支付的相关参数时,报了这么一个错误:appid and openid not match. 字面意思很容易理解,就是appid与openi ...