异步上传文件插件AjaxFileUploader在Asp.net MVC中应用

1. 下载插件

异步上传插件AjaxFileUploader,下载地址:http://phpletter.com/DOWNLOAD 

选择上面的2.1版本,下载。

2. 服务端代码

在HomeController中添加一个方法:

        [HttpPost]
        public string UpLoad(HttpPostedFileBase file)
        {
       string message="";
if (file == null) { message = "没有文件!"; } var fileName = Path.Combine(Request.MapPath("~/UploadFiles"), Path.GetFileName(file.FileName)); try { file.SaveAs(fileName); message = "上传成功!"; } catch { message = "上传异常 !" + Err.Message; }
       return message; }

注意要添加引用 using System.IO;

3. 客户端Html代码:

<div>
    <input type="file" id="file" name="file" />
    <img src="../images/loading.gif" width="20px" height="20px" id="loading" style="display: none;">
    <span id="mydiv" style="color: green;"></span>
    <br />
    <input type="button" value="上传" onclick="ajaxFileUploads();">
</div>
<script type="text/javascript">
    function ajaxFileUploads() {
        //starting setting some animation when the ajax starts and completes
        $("#loading").ajaxStart(function () {
            $(this).show();
        }).ajaxComplete(function () {
            $(this).hide();
        });
        $.ajaxFileUpload({
                url: '/home/UpLoad',
                secureuri: false,
                fileElementId: 'file',
                dataType: 'text',
                success: function (data, status) {
            alert(data);
                },
                error: function (data, status, e) {
                    alert(e);
                }
            }
        )
        return false;
    }
</script>

在客户端要添加 ajaxfileupload.js、ajaxfileupload.css、loading.gif 这三个文件。

另外要在更目录下面增加一个文件夹UploadFiles。

原文地址:https://www.cnblogs.com/liquanchun/p/2847794.html