本篇体验MVC上传文件,从表单上传过渡到jquery异步上传。
MVC最基本的上传文件是通过form表单提交方式
□ 前台视图部分
<% using(Html.BeginForm("FileUpload", "FileUpload", FormMethod.Post, new {enctype = "multipart/form-data"}) {)%>
<input name ="uploadFile" type="file" />
<input type="submit" value="Upload File" />
<%}%>
□ 控制器部分
[HttpMethod.Post]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
if(uploadFile.ContenctLength > 0)
{
//获得保存路径
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
}
return View();
}
但整个页面会刷新,面对比较单一、简单的需求的时候,有其价值。但在实际项目中,当然是希望通过异步方式来实现。
使用jQuery文件上传插件实现异步上传
□ 思路
1、使用jQuery文件上传插件的fileupload()方法,为type="file"的input设置url,dataType等,并把数据交给一个全局变量var jqXHRData。
2、点击上传按钮,提交数据 jqXHRData.submit()
3、控制器方法负责把文件上传到指定文件夹
□ 需要引用的js文件
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/jquery-ui-1.9.2.min.js"></script>
<script src="~/Scripts/jquery.fileupload.js"></script>
<script src="~/Scripts/jquery.fileupload-ui.js"></script>
<script src="~/Scripts/jquery.iframe-transport.js"></script>
□ View Model
属性类型为HttpPostedFileBase。
using System.Web;
namespace MvcApplication1.Models
{
public class MyModel
{
public HttpPostedFileBase MyFile { get; set; }
}
}
□ HomeController
using System.Web.Mvc;
namespace MvcApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
□ Home/Index.cshtml
@model MvcApplication1.Models.MyModel
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h5>简单上传</h5>
<div>
@Html.TextBoxFor(m => m.MyFile, new {id="simple",type="file"} ) <br/>
<a href="#" id="simpleupload">开始简单上传</a>
</div>
<h5>检查文件类型和尺寸</h5>
<div>
<input type="file" name="myFile" id="check" /> <br/>
<a href="#" id="checkupload">开始检查并上传</a>
</div>
@section scripts
{
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/jquery-ui-1.9.2.min.js"></script>
<script src="~/Scripts/jquery.fileupload.js"></script>
<script src="~/Scripts/jquery.fileupload-ui.js"></script>
<script src="~/Scripts/jquery.iframe-transport.js"></script>
<script type="text/javascript">
var jqXHRData;
$(function() {
initSimpleFileUpload();
initFileUploadWithCheck();
//简单上传
$('#simpleupload').on('click', function() {
if (jqXHRData) {
jqXHRData.submit();
}
return false;
});
//检查图片文件类型和大小
$('#checkupload').on('click', function() {
if (jqXHRData) {
var isStartUpload = true;
var uploadFile = jqXHRData.files[0];
if (!(/.(gif|jpg|jpeg|tiff|png)$/i).test(uploadFile.name)) {
alert('允许图片格式gif|jpg|jpeg|tiff|png');
isStartUpload = false;
} else if (uploadFile.size > 4000000) { // 4mb
alert('图片尺寸不能大于4 MB');
isStartUpload = false;
}
if (isStartUpload) {
jqXHRData.submit();
}
}
return false;
});
});
//简单上传
function initSimpleFileUpload() {
$('#simple').fileupload({
url: '@Url.Action("UploadFile","File")',
dataType: 'json',
add: function(e, data) {
jqXHRData = data;
},
done: function(event, data) {
if (data.result.isUploaded) {
alert(data.result.message);
} else {
alert(data.result.message);
}
},
fail: function(event, data) {
if (data.files[0].error) {
alert(data.files[0].error);
}
}
});
}
//检查图片文件类型和大小
function initFileUploadWithCheck() {
$('#check').fileupload({
url: '@Url.Action("UploadFile","File")',
dataType: 'json',
add: function (e, data) {
jqXHRData = data;
},
done: function (event, data) {
if (data.result.isUploaded) {
alert(data.result.message);
} else {
alert(data.result.message);
}
},
fail: function (event, data) {
if (data.files[0].error) {
alert(data.files[0].error);
}
}
});
}
</script>
}
□ FileController
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication1.Controllers
{
public class FileController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult UploadFile()
{
HttpPostedFileBase myFile = Request.Files["MyFile"];
bool isUploaded = false;
string message = "上传失败";
if (myFile != null && myFile.ContentLength != 0)
{
string pathForSaving = Server.MapPath("~/Uploads");
if (this.CreateFolderIfNeeded(pathForSaving))
{
try
{
myFile.SaveAs(Path.Combine(pathForSaving, myFile.FileName));
isUploaded = true;
message = "上传成功";
}
catch (Exception ex)
{
message = string.Format("上传文件失败:{0}", ex.Message);
}
}
}
return Json(new { isUploaded = isUploaded, message = message });
}
/// <summary>
/// 检查是否要创建上传文件夹
/// </summary>
/// <param name="path">路径</param>
/// <returns></returns>
private bool CreateFolderIfNeeded(string path)
{
bool result = true;
if (!Directory.Exists(path))
{
try
{
Directory.CreateDirectory(path);
}
catch (Exception)
{
//TODO:处理异常
result = false;
}
}
return result;
}
}
}
□ 另外,配置文件中需要设置允许的最大文件尺寸
<system.web>
<!--10240 Kb = 10 MB-->
<httpRuntime targetFramework="4.5" maxRequestLength= "10240" />
...
</system.web>
□ 结果
上传成功后,多了Uploads文件夹:
上传PDF格式,出现报错: