asp.net mvc+html实现文件上传

文件上传其实很多的组件效果都很不错,像webupload等等,最近的项目不让用,那就自己写呗,不多说了,上代码。

  1,前端代码:

  <form id="form1" enctype="multipart/form-data" method="post">
                            <div class="row">
                                <input type="file" name="fileToUpload" id="fileToUpload" onchange="fileSelected();">
                            </div>
                            <input hidden="hidden" id="hid_newFileName" value="" />
                            <div id="progressNumber"></div>
                        </form>

2,脚本处理


<script type="text/javascript">

    function saveExceldata() {        
        var newFileName = document.getElementById('hid_newFileName').value; 
        if (newFileName != "") {
          
            $.ajax({
                type: "POST",
                dataType: 'json',
                url: bootPATH.substring(0, bootPATH.indexOf("S")) + "PlanManageMent/ArrangeContainersIn/saveExceldata",
                data: { "fileName": newFileName },
                beforeSend: function () { 
                },
                error: function () {    
                },
                complete: function () {
                    
                },
                success: function (data) {
                    if (data.state == 0) {
                        mini.alert("导入失败:" + data.message);
                    }
                    else {
                        mini.alert("导入成功");
                    }
                }
            });
        }
        else {
            mini.alert("请选择excel文件");
        }
    }

    function fileSelected() {
        var file = document.getElementById('fileToUpload').files[0];
        if (file) {
            var exName = file.name.split('.')[1].toLowerCase();
            debugger
            if (exName != "xls") {
                document.getElementById("fileToUpload").value = "";
                document.getElementById("hid_newFileName").value = "";
                mini.alert("请选择excel文件");
                return;
            }
            else {
                uploadFile();
            }

            //var fileSize = 0;
            //if (file.size > 1024 * 1024)
            //    fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
            //else
            //    fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
            //document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
            //alert(file.name);
            //document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
            //document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
        }
    }

    function uploadFile() {
        
        var fd = new FormData();
        fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
        var xhr = new XMLHttpRequest();
        xhr.upload.addEventListener("progress", uploadProgress, false);
        xhr.addEventListener("load", uploadComplete, false);
        xhr.addEventListener("error", uploadFailed, false);
        xhr.addEventListener("abort", uploadCanceled, false);
        xhr.open("POST", bootPATH.substring(0, bootPATH.indexOf("S")) + "PlanManageMent/ArrangeContainersIn/UploadExcelSave");  //路径注意是自己
        xhr.send(fd);
    }

    //进度
    function uploadProgress(evt) {
        if (evt.lengthComputable) {
            var percentComplete = Math.round(evt.loaded * 100 / evt.total);
            document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
        } else {
            document.getElementById('progressNumber').innerHTML = 'unable to compute';
        }
    }

    function uploadComplete(evt) {
         
        /* 服务器端返回响应时候触发event事件*/
        var res = evt.target.responseText
        var jsondata = JSON.parse(res);
        if (jsondata.state == 0) {
            document.getElementById("hid_newFileName").value = jsondata.filename;
        }
    }

    function uploadFailed(evt) {
        mini.alert("上传失败");
    }

    function uploadCanceled(evt) {
        // mini.alert("取消上传");
    }
</script>

3,后端处理

       [HttpPost]
        public ActionResult UploadExcelSave()
        {
            string fileName = string.Empty;
            if (Request.Files.Count > 0)
            {
                var file = Request.Files[0];
                fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Path.GetFileName(file.FileName);
                var folderPath = Path.Combine(Server.MapPath("~/data/Excel"));
                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }
                file.SaveAs(folderPath + "/" + fileName);
            }
            return Json(new { state = 0, filename = fileName });
        }

这里最后保存了,然后把文件的名称返回出去,如果是图片,正好可以把图片显示出去! (当然也可以用js在存到服务端之前处理后显示)

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值