ajax无刷新上传文件MVC

本文介绍了一个简单的文件上传功能实现,包括前端使用JavaScript进行文件选择和上传触发,通过Ajax发送POST请求到服务器,以及后端控制器接收并处理上传的文件。文章展示了如何在客户端获取文件,并将文件数据发送到服务器端,在服务器端接收文件并保存到指定目录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@{
    ViewBag.Title = " Assistant";
    //Layout = null;
}
<script type="text/javascript">

        $(document).ready(function () {
            $("#fileButton").click(function () {
                var files = $("#fileInput").get(0).files;
                var fileData = new FormData();

                for (var i = 0; i < files.length; i++) {
                    fileData.append("fileInput", files[i]);
                }

                $.ajax({
                    type: "POST",
                    url: "/Document/UploadFiles",
                    dataType: "json",
                    contentType: false, // Not to set any content header
                    processData: false, // Not to process data
                    data: fileData,
                    success: function (result, status, xhr) {
                        alert(result);
                        $("#fileInput").val("");
                    },
                    error: function (xhr, status, error) {
                        alert(status);
                    }
                });
            });

            $(document).ajaxStart(function () {
                //$("#loadingImg").show();
               // $("#fileButton").prop('disabled', true);
            });

            $(document).ajaxStop(function () {
                //$("#loadingImg").hide();
               // $("#fileButton").prop('disabled', false);
               // $("#fileInput").val("");
            });

        });

</script>

<!--Attachment 5-->
<div class="content">


                    <textarea id="txtID1" cols="60" rows="3" style="color:black"></textarea>

                        <div class="row">
                            <input type="file" id="fileInput" multiple />
                            <input type="button" id="fileButton" value="Upload Files" /><br />
                        </div>
</div>


controller层

        [HttpPost]
        public ActionResult UploadFiles()
        {
            string path = Server.MapPath("~/WorkFolder/Upload/Inspection/");
            HttpFileCollectionBase files = Request.Files;
            for (int i = 0; i < files.Count; i++)
            {
                HttpPostedFileBase file = files[i];
                file.SaveAs(path + file.FileName);
            }
            return Json(files.Count + " Files Uploaded!");
        }


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值