MVC4 文件上传的两种方式,默认提交表单方式和AJAX异步方式(精华)

如题,将为大家展示如何使用MVC4实现文件上传的两种方式


一、第一种方式(默认提交表单方式)

首先,新建MVC4工程,如下图所示:

然后,添加控制器HomeController,如下图所示:

由于使用MVC自带的功能,我们可以很方便的将从form中获取数据填充到一个Model实体中,因此我们先写一个FileInfo实体类。

在Models文件夹中添加一个FileInfo.cs类:

using System.Web;

namespace MvcFileUpload.Models
{
    public class FileInfo
    {
        public string FileName { get; set; }
        public HttpPostedFileBase File { get; set; }
    }
}

在Home控制器中,我们添加请求的代码如下:

public ActionResult Index()
{
    return View();
}

[HttpPost]
public ActionResult Index(FileInfo info)
{
    try
    {
        string savePath = "C://" + info.FileName + Path.GetExtension(info.File.FileName);
        info.File.SaveAs(savePath);
        return Json("上传成功");
    }
    catch (Exception e)
    {
        return Json("上传失败");
    }
}

在Home/Index.cshtml中的代码为:

@model MvcFileUpload.Models.FileInfo
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>默认提交表单方式-上传文件</title>
    <link href="~/Content/bootstrap-3.3.5-dist/css/bootstrap.min.css" rel="stylesheet"
        type="text/css" />
</head>
<body>
    <div class="container">
        <div class="row">
            <h2>默认提交表单方式-上传文件</h2>
            @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @class = "form-horizontal", enctype = "multipart/form-data" }))
            {
                <div class="form-group">
                    <label for="File">
                        选择文件</label>
                    @Html.TextBoxFor(m => Model.File, new { type = "file" })
                </div>
                <div class="form-group">
                    <label for="FileName">
                        文件名</label>
                    @Html.TextBoxFor(m => Model.FileName, new { @class = "form-control", placeholder = "请输入要上传的文件名" })
                </div>
                <div class="form-group">
                    <button type="submit" class="btn btn-info">
                        上传</button>
                </div>
            }
        </div>
    </div>
    @Scripts.Render("~/bundles/jquery")
    <script src="~/Scripts/jquery.form.js" type="text/javascript"></script>
    <script src="../../Content/bootstrap-3.3.5-dist/js/bootstrap.min.js" type="text/javascript"></script>
</body>
</html>

试着跑一下程序吧。第一种方式成功实现!接下来讨论第二种实现方式。

二、第二种方式(AJAX异步方式)

为了节省时间,我们在控制器Home中新建Index2视图

并在HomeController中添加如下代码:

public ActionResult Index2()
{
    return View();
}

[HttpPost]
public ActionResult AjaxUpload()
{
    try
    {
        var postedFile = Request.Files[0];//只示范上传一个文件
        if (postedFile == null || postedFile.ContentLength <= 0) return Json("请选择要上传的文件");
        string savePath = "C://" + Request["filename"] + Path.GetExtension(postedFile.FileName);
        postedFile.SaveAs(savePath);
        return Json("AJAX上传成功");
    }
    catch
    {
        return Json("AJAX上传失败");
    }
}

然后在Index2视图中的代码如下:

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>AJAX异步方式-上传文件</title>
    <link href="~/Content/bootstrap-3.3.5-dist/css/bootstrap.min.css" rel="stylesheet"
        type="text/css" />
    <style>
        .progress
        {
            position: relative;
            width: 300px;
            border: 1px solid #0db09b;
            padding: 0;
            border-radius: 3px;
        }
        .bar
        {
            background-color: #0db09b;
            width: 0;
            height: 20px;
            border-radius: 3px;
        }
        .percent
        {
            position: absolute;
            display: inline-block;
            top: 0;
            left: 47%;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row">
            <h2>
                AJAX异步方式-上传文件</h2>
            @using (Html.BeginForm("AjaxUpload", "Home", FormMethod.Post, new { id = "uploadForm", @class = "form-horizontal", enctype = "multipart/form-data" }))
            {
                <div class="form-group">
                    <label for="file">
                        选择文件</label>
                    <input id="file" name="file" type="file" />
                </div>
                <div class="form-group">
                    <label for="filename">
                        文件名</label>
                    <input id="filename" name="filename" class="form-control" placeholder="请输入要上传的文件名"
                        type="text" />
                </div>
                <div class="form-group">
                    <button type="submit" class="btn btn-info">
                        上传</button>
                </div>
            }
        </div>
        <div class="row">
            <div class="progress">
                <div class="bar">
                </div>
                <div class="percent">
                    0%</div>
            </div>
            <div id="status">
            </div>
        </div>
    </div>
    @Scripts.Render("~/bundles/jquery")
    <script src="~/Scripts/jquery.form.js" type="text/javascript"></script>
    <script src="../../Content/bootstrap-3.3.5-dist/js/bootstrap.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        (function () {
            var bar = $('.bar');
            var percent = $('.percent');
            var status = $('#status');
            $('#uploadForm').on('submit', function (e) {
                e.preventDefault(); // <-- important
                $(this).ajaxSubmit({
                    beforeSend: function () {
                        status.empty();
                        var percentVal = '0%';
                        bar.width(percentVal);
                        percent.html(percentVal);
                    },
                    uploadProgress: function (event, position, total, percentComplete) {
                        var percentVal = percentComplete + '%';
                        bar.width(percentVal);
                        percent.html(percentVal);
                    },
                    success: function () {
                        var percentVal = '100%';
                        bar.width(percentVal);
                        percent.html(percentVal);
                    },
                    complete: function (xhr) {
                        status.html(xhr.responseText);
                    }
                });
            });
        })();
    </script>
</body>
</html>

到此,就能实现AJAX异步上传文件了,还有进度条呢,是不是很叼啊~~!:-)

注意:

1.使用到了jquery.min.js、jquery.form.min.js、bootstrap.min.css、bootstrap.min.js、

2.如果想做上传限制,可以在web.config中添加

<system.web>
    <httpRuntime executionTimeout= "9000"   maxRequestLength="524288000"   useFullyQualifiedRedirectUrl= "false " minFreeThreads= "8 "   minLocalRequestFreeThreads= "4 "   appRequestQueueLimit= "100 "/>
</system.web>

完美~!!欢迎转载~~!分享快乐~~!

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值